Pages

Friday, June 29, 2012

How to consume custom JSON using Spring MVC

When using Spring MVC, you get number of things free, one of them is Jackson, that will produce JSON from your classes  (it happens automatically if you use <mvc> namespace) and consume JSON on the inbound request

But sometimes, you need to consume a custom JSON, that you do not have a class dedicated for it, hence it is not driven by Jackson annotations.
To do that, simply define a method in your Controller:


@RequestMapping(value = "/customer/{id}", method = RequestMethod.POST)
@ResponseBody
public onPost(@PathVariable("id") String id, @RequestBody String body) {
ObjectMapper mapper = new ObjectMapper();
try {
Map<String, Object> readValue = mapper.readValue(body, Map.class);
logger.info("Object is {}", readValue.getClass().getName());
} catch (Exception e) {
e.printStackTrace();
}
}


Spring will bind the body of the request to a java.lang.String and ObjectMapper will convert this String to a Map, so you could access it however you like.
In practice, Object (the value in the map) could be another Map, so you would have to traverse it as well.

No comments: