【问题标题】:Can Spring MVC deserialize JSON which can be object or array?Spring MVC可以反序列化可以是对象或数组的JSON吗?
【发布时间】:2015-05-08 12:53:57
【问题描述】:

我有控制器在请求正文中接收 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, ...) {
   ...
}

如果不是,那么解析和验证这类消息的优雅方式是什么?

【问题讨论】:

标签: java json spring spring-mvc jackson


【解决方案1】:

所以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","");
}

【讨论】:

    猜你喜欢
    • 2019-12-09
    • 1970-01-01
    • 1970-01-01
    • 2022-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多