Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 762 Vote(s) - 3.57 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to pass List<String> in post method using Spring MVC?

#1
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"]}`
Reply

#2
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){
...
}



Reply

#3
I had the same use case,
You can change your method defination in the following way :

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

**The only problem is it accepts any key in place of "fruits" but You can easily get rid of a wrapper if it is not big functionality.**



Reply

#4
You can pass input as `["apple","orange"] `if you want to leave the method as it is.

It worked for me with a similar method signature.
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through