我让控制器在请求体中接收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, ...) {
...
}
如果没有,解析和验证这类消息的优雅方式是什么?
答案 0 :(得分:2)
所以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","");
}