简体   繁体   中英

Can Spring MVC deserialize JSON which can be object or array?

I have controller receiving JSON in request body, which can be object or array of objects. For example:

{
  "id" : 1,
  "name" : "Nick",
  "surname" : "Cave"
}

and

[
 {
   "id" : 1,
   "name" : "Nick",
   "surname" : "Cave"
 },
 {
   "id" : 2,
   "name" : "Jack",
   "surname" : "White"
 }
]

Is there any way to force Spring to deserialize JSON to object in the similar way to object alone?

@RequestMapping(value = "/", method = RequestMethod.POST)
public void postController(@RequestBody User user, ...) {
   ...
}

If not, what is the elegant way of parsing and validating those kind of messages?

So 1) add to 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","");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM