如何使用 Spring MVC 在 post 方法中传递 List<String>?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34789357/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 00:55:56  来源:igfitidea点击:

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

springrestspring-mvc

提问by user2359634

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

我需要在POST方法的请求正文中传递一个值列表,但我得到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"]}

我使用的 JSON 是: {"fruits":["apple","orange"]}

回答by wcislo

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

您使用了错误的 JSON。在这种情况下,您应该使用如下所示的 JSON:

["orange", "apple"]

If you have to accept JSON in that form :

如果您必须接受该形式的 JSON:

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

回答by Mitesh Ukate

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.

唯一的问题是它接受任何键来代替“水果”,但是如果它不是很大的功能,您可以轻松摆脱包装器。

回答by Ganesh Bhattachan

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

您可以传递输入,就["apple","orange"]好像您想保留该方法一样。

It worked for me with a similar method signature.

它使用类似的方法签名对我有用。