How to pass List in post method using Spring MVC?

前端 未结 3 978
旧时难觅i
旧时难觅i 2020-12-13 13:32

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:



        
相关标签:
3条回答
  • 2020-12-13 13:54

    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.

    0 讨论(0)
  • 2020-12-13 14:02

    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){
    ...
    }
    
    0 讨论(0)
  • 2020-12-13 14:02

    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.

    0 讨论(0)
提交回复
热议问题