Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass List<String> in post method using Spring MVC?

I need to pass a list of values in the request body of POST method but I get 400: Bad Request error.

Below is my sample code:

@RequestMapping(value = "/saveFruits", method = RequestMethod.POST,      consumes = "application/json") @ResponseBody public ResultObject saveFruits(@RequestBody List<String> fruits) {     ... } 

The JSON I am using is: {"fruits":["apple","orange"]}

like image 791
user2359634 Avatar asked Jan 14 '16 12:01

user2359634


1 Answers

You are using wrong JSON. In this case you should use JSON that looks like this:

["orange", "apple"] 

If you have to accept JSON in that form :

{"fruits":["apple","orange"]} 

You'll have to create wrapper object:

public class FruitWrapper{      List<String> fruits;      //getter     //setter } 

and then your controller method should look like this:

@RequestMapping(value = "/saveFruits", method = RequestMethod.POST,      consumes = "application/json") @ResponseBody public ResultObject saveFruits(@RequestBody FruitWrapper fruits){ ... } 
like image 64
wcislo Avatar answered Sep 21 '22 07:09

wcislo