Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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(...) {
    ...
}
like image 504
Naresh Avatar asked Oct 26 '25 02:10

Naresh


2 Answers

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")
like image 133
JB Nizet Avatar answered Oct 29 '25 03:10

JB Nizet


You can return a generic List.

public List<?> getTransactions() 
{
}

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

like image 34
Paul John Avatar answered Oct 29 '25 04:10

Paul John