Java spring mvc 控制器接受具有可变数量的键/值的 JSON 对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20790634/
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
spring mvc controller accept JSON object with variable number of keys/values
提问by Barry
I know the JSON object I need to accept will always be single keys and values. I attempted to write my Spring MVC controller with @RequestBody Map and @RequestBody Map however I always get 400 Bad Request. When I change my @RequestBody to a String I see my data come through and no Bad Request response is returned.Is it possible to write something to accept an arbitrary JSON object that will always conform to the contract of being a single key to a single value?
我知道我需要接受的 JSON 对象将始终是单个键和值。我尝试使用 @RequestBody Map 和 @RequestBody Map 编写我的 Spring MVC 控制器,但是我总是收到 400 Bad Request。当我将 @RequestBody 更改为字符串时,我看到我的数据通过并且没有返回错误请求响应。价值?
@RequestMapping(value = "/advancedSearch", method = RequestMethod.POST,consumes ="application/json",produces = "application/json")
@ResponseBody
public MyResponse performAdvancedSearch(@RequestBody String advancedFormData) throws Exception{
this is the mapping that is working right now with String...
这是现在与字符串一起工作的映射......
sample JSON-
示例 JSON-
{"name":"frank","Type":"Lumber"}
when posting from front-end I call JSON.stringify() to create data.Again, the JSON will always be simple like this no nested lists/objects just straight key/values. The server side just never knows how many key value pairs will come in and it has no knowledge of all the potential keys so I can't create a simple POJO.
从前端发布时,我调用 JSON.stringify() 来创建数据。同样,JSON 将始终如此简单,没有嵌套的列表/对象,只有直接的键/值。服务器端永远不知道会有多少键值对进入,并且它不知道所有潜在的键,所以我无法创建一个简单的 POJO。
回答by Sotirios Delimanolis
Make your life simple and create a class
让你的生活变得简单,创建一个班级
public class AdvancedFormData
private String name;
private String type; // make it lower case in your JSON too
// appropriate getters and setters and a no-arg constructor for Hymanson
}
and use
并使用
public MyResponse performAdvancedSearch(@RequestBody AdvancedFormData advancedFormData) throws Exception{