Building a RESTful Service that returns JSON using the Spring Framework
In my previous post I did a very simple example of Building a very simple Java REST API with Spring 3.x. Now I’d like to build on that and make it a little more useful and show some of the great features available in the Spring Framework that makes things easier and quicker. In this example we’ll add a new method to the SimpleRestController class that returns a POJO as a JSON document and we’ll never have to worry about calling any serializing API in our code. First let’s write the code and then we’ll look at what is happening:
package com.fouzi.blog; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; @Controller public class SimpleRestController { @RequestMapping(value = "/simple", method = RequestMethod.GET) @ResponseBody public String handleSimple() { return "Hello Simple World!"; } @RequestMapping(value = "/simple/pojo_hashmap", method = RequestMethod.GET) @ResponseBody public HashMap handleReturnHashMapJson() { HashMap theHashMap = new HashMap(); theHashMap.put("Great Coffee", "Barefoot"); theHashMap.put("Bad Coffee", "Starbucks"); return theHashMap; } }
If you run this and try to connect to the resource localhost:8080/simple/pojo_hashmap you’ll get an HTTP 406 Not Acceptable Error. So what gives? Well the trick here lies in understanding what Springsource is doing behind the scenes. To serialize a POJO and have it sent as part of the ResponseBody Springsource needs a library to do this. The library of choice her is the Jackson JSON library. So to get this working you will need to add the following maven dependency to your pom.xml file:
<!-- Jackson JSON Processor -->
<dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.9.0</version> </dependency>
By including the Jackson JSON processor the Spring Framework will then serialize any POJO into JSON, even your own home grown User.java or whatever Java objects you have created. Now when you connect to localhost:8080/simple/pojo_hashmap you will get a response like this:
{"Great Coffee":"Barefoot","Bad Coffee":"Starbucks"}
And that’s all you need to do to start serving up JSON from your Java APIs!