如何传递List< String>在使用Spring MVC的发布方法中? [英] How to pass List<String> in post method using Spring MVC?

查看:360
本文介绍了如何传递List< String>在使用Spring MVC的发布方法中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在POST方法的请求主体中传递值列表,但得到400: Bad Request error.

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

下面是我的示例代码:

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

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

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

推荐答案

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

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

["orange", "apple"]

如果您必须以这种形式接受JSON:

If you have to accept JSON in that form :

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

您必须创建包装对象:

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

这篇关于如何传递List&lt; String&gt;在使用Spring MVC的发布方法中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆