Azim Azim -5 years ago 373
JSON Question

Best way to use Json object from @requestBody in controller instead of mapping to POJO

Usually we map object from @RequestBody into some POJO at controller. In order to map into POJO we should know the fields from the @RequestBody object. So, my question is what could be the best way to use this object inside controller IF YOU DON'T KNOW THE FIELDS INSIDE REQUESTBODY.

Is it like?

@RequestMapping(value = "/students", method = RequestMethod.POST, consumes = "application/json")
public @ResponseBody Student getStudent(@RequestBody String json) {
// then parse the json string into object...

Please share some innovative ideas. Thanks in advance.

Answer Source

Updated Answer

Based on the updated description of the question and if you are already using Jackson then following code will give you a Map of the json string.

ObjectMapper mapper = new ObjectMapper();
Map<String,Object> map = mapper.readValue(json, Map.class);

Note: I have created a new instance of ObjectMapper, you can use the ObjectMapper bean if you have already defined one for your application.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download