Spring MVC 可以反序列化 JSON 可以是对象还是数组?
Can Spring MVC deserialize JSON which can be object or array?
我有控制器在请求正文中接收 JSON,它可以是对象或对象数组。例如:
{
"id" : 1,
"name" : "Nick",
"surname" : "Cave"
}
和
[
{
"id" : 1,
"name" : "Nick",
"surname" : "Cave"
},
{
"id" : 2,
"name" : "Jack",
"surname" : "White"
}
]
是否有任何方法可以强制 Spring 以类似于单独对象的方式将 JSON 反序列化为对象?
@RequestMapping(value = "/", method = RequestMethod.POST)
public void postController(@RequestBody User user, ...) {
...
}
如果不是,解析和验证此类消息的优雅方式是什么?
所以 1) 添加到 maven :
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
2)
@RequestMapping(value = "/addPerson",
method = RequestMethod.POST,
headers = {"Content-type=application/json"})
@ResponseBody
public JsonResponse addPerson(@RequestBody Person person) {
logger.debug(person.toString());
return new JsonResponse("OK","");
}
我有控制器在请求正文中接收 JSON,它可以是对象或对象数组。例如:
{
"id" : 1,
"name" : "Nick",
"surname" : "Cave"
}
和
[
{
"id" : 1,
"name" : "Nick",
"surname" : "Cave"
},
{
"id" : 2,
"name" : "Jack",
"surname" : "White"
}
]
是否有任何方法可以强制 Spring 以类似于单独对象的方式将 JSON 反序列化为对象?
@RequestMapping(value = "/", method = RequestMethod.POST)
public void postController(@RequestBody User user, ...) {
...
}
如果不是,解析和验证此类消息的优雅方式是什么?
所以 1) 添加到 maven :
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
2)
@RequestMapping(value = "/addPerson",
method = RequestMethod.POST,
headers = {"Content-type=application/json"})
@ResponseBody
public JsonResponse addPerson(@RequestBody Person person) {
logger.debug(person.toString());
return new JsonResponse("OK","");
}