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.

Tuesday, June 26, 2012

How to use Spring Resources in WAR Example

Problem: Assume you have a some resources in your WAR file, that you want to use in run time, for example accessing XML files and printing it's content, or reading some meta-data and using it.

Solution: Spring provided an useful Resource abstraction, that can be used. To obtain a reference to a service that will allow access to resource, you can use:

@Autowired
private ResourcePatternResolver resourceLoader = null;


Spring will inject a bean that implements this interface, in practice it would actually be a reference for ApplicationContext (ApplicationContext must implement ResourcePatternResolver interface)

and then you can get an array of resources by using:

Resource[] resources = resourceLoader.getResources("resources/my-xml-files/**");

After that, you can iterate over the resources and easily perform

resource.getInputStream()

to read the contents.

Good luck