[英]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","");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.