Naresh
Naresh

Reputation: 25773

Spring MVC - how to return different JSON responses based on query parameters?

I am implementing a REST api using Spring MVC. The requirement is:

  1. /transactions returns an array of transactions.
  2. /transactions?groupByCategory returns transactions grouped by categories.

For example request #1 returns:

[
    { "id": 1, "category": "auto", "amount": 100 },
    { "id": 2, "category": "misc", "amount": 200 },
    { "id": 3, "category": "auto", "amount": 300 }
]

whereas request #2 groups this result by category and returns the sum of each category:

[
    { "category": "auto", "amount": 400 },
    { "category": "misc", "amount": 200 }
]

Obviously the return value from these requests is of different types. How do I do this in Spring MVC? So far I have:

@RequestMapping("/transactions")
public List<Transaction> getTransactions(
        @RequestParam(value="groupByCategory", required=false) String groupByCategory
        ) {

    ...
}

But this fixes the return type to List<Transaction>. How do I accommodate the second type: List<TransactionSummaryByCategory>?

Edit: I found one solution, i.e. to specify the return type as Object. That seems to work and the response is serialized correctly based on the object type. However, I wonder if this is a best practice!

public Object getTransactions(...) {
    ...
}

Upvotes: 4

Views: 2334

Answers (2)

JB Nizet
JB Nizet

Reputation: 691715

You can simply provide two methods in your controller. First one returning List<Transaction> mapped using

@RequestMapping("/transactions")

and the second one returning List<TransactionSummaryByCategory> and mapped using

@RequestMapping(value = "/transactions", params = "groupByCategory")

Upvotes: 6

Paul John
Paul John

Reputation: 1661

You can return a generic List.

public List<?> getTransactions() 
{
}

Based on the request params you can populate the list with the appropriate objects

Upvotes: 1

Related Questions