Thursday, January 2, 2014

Creating a restful JSON web service which sends and receive objects

I recently wanted to create a restful JSON web service which was able to both receive and return regular java objects.

I was curious how to do it using the @RequestBody and @ResponseBody annotations, since this seemed like the most straightforward approach. Luckily, I found a nice link which basically explains the whole process, and adds in some Javascript for good measure. Here's the link:

http://codetutr.com/2013/04/09/spring-mvc-easy-rest-based-json-services-with-responsebody/

Although the code posted doesn't include using both annotions in the same method, it is explained in the comments section. I implemented it as follows:

@RequestMapping(value="person", method=RequestMethod.POST)
@ResponseBody
public Person postPerson(@RequestBody Person person) {    
    System.out.println("posting " + person.toString());
    personService.save(person);
    return person;


}

Note how both the input and output parameters are Java objects. This serialization to and from JSON in made possible by the inclusion of a jackson-mapper jar file in the classpath. Also, annotations must be turned on, and the request from the application must include a header indicating it's expecting JSON. See the posted link for more details. 

No comments:

Post a Comment