Returning JSON in Java with Spring MVC

Posted on 28-04-2013 21:06 by graham
This tutorial describes how to return JSON using Spring MVC framework. It describes two approaches: one that uses Jackson to automatically convert an object of any type to JSON, and another in which JSON is manually written to the response.

Automatic conversion of objects to JSON


This is a simpler approach, however, it requires you to use a Jackson JSON library.

The first thing to do is to attach the library to your code. If you are using Maven, all you need to do is add the following dependency to you pom.xml file:
pom.xml
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.7.1</version>
</dependency>

Then, in your controller you can return an object of any type in the action method and it will be automatically converted to JSON:
SampleController.java
@RequestMapping(value = "/getuser", method = RequestMethod.GET)
public @ResponseBody User getUser()
{
User user = new User();
user.setName("John Morris");

// user object will be automatically converted to JSON
return user;
}

This will result in the following JSON code being returned:
{ "name": "John Morris" }

Writing JSON directly to the response


This method is more generic. Its advantage is that it does not require you to use Jackson.

To do the same as above, our controller code looks like this:
SampleController.java
@RequestMapping(value = "/getuser", method = RequestMethod.GET)
@ResponseBody
public void getUser(HttpServletResponse response)
{
User user = new User();
user.setName("John Morris");

PrintWriter out = null;
try
{
out = response.getWriter();
}
catch (IOException e)
{
// handle the exception somehow
e.printStackTrace();
}

// we need to manually convert the object to JSON using JSONValue
String jsonString - JSONValue.toJSONString(user);

// optinally, we could even build the JSON manually"
// String jsonString = "{ \"name\": \"" + user.getName() + "\" }";

out.write(jsonString);
}

Parsing JSON results


If you need to know how to parse such JSON results, take a look at our tutorial about calling JSON Ajax.
Comments

 

Add comment

Has this tutorial been helpful to you? Or do you see anything wrong? We appreciate your opinion!
Your comment:
Show formatting hints
HTML is disallowed, but in your text you can use the following markup
  • [code][/code] for a block of code
  • [tt][/tt] for inline code
  • [link]link href|link anchor[/link] for links
  • [b][/b] for bold text
Email:
+ Ask a question
If you have a technical question related to programming and computers, ask it here. Other users will help you solve it!
Unanswered questions
Share your knowledge by helping others solve their problems