Spring MVC Tip: Returning JSON from a Spring Controller

In my Spring MVC and Rest post, I walked through the creation of a RESTful web service with Spring MVC. Let’s now take a look at JSON.

Spring MVC, from version 3, allows you to return objects directly converted into JSON using the @ResponseBody annotation in a Controller as shown here:

@RequestMapping(method=RequestMethod.GET, value =”/movie/{name})  
public @ResponseBody Movie getMovie(@PathVariable String name, Model model){ 
    return new Movie(name);

In this way, AJAX interactions can be simplified, since you can deal with JSON objects after you interrogate a RESTful web service. In order to achieve that, assuming you are using Maven, you need to include the Jackson mapper dependency to your POM file as shown here:

  <groupId> org.codehaus.jackson</groupId>

After that, you need to add to your Spring configuration file the mvc:annotation-driven configuration element and the bean with class ContentNegotiatingViewResolver:

<mvc:annotation-driven />
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
  <property name="mediaTypes">
      <entry key="html" value="text/html"/>
      <entry key="json" value="application/json"/>
  <property name="viewResolvers">
      <bean class="org.springframework.web.servlet.view.UrlBasedViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
  <property name="defaultViews">
      <bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView">
        <property name="prefixJson" value="true"/>

ContentNegotiatingViewResolver, based on the supported mediaType, will determine the right view resolver. In this case the UrlBasedViewResolver would handle text/html content and the MappingJacksonView would handle application/json content. An example of a simple JSON object, containing just the name attribute, returned by the above controller could be:

{name : “Titanic”}

On the client-side, here is some JavaScript code (using jQuery) invoking the web service defined in the first snippet:

$.get(“http://www.example.com/movie/titanic”, function(data){
	// data is a JSON object

The callback will hold the JSON object coming from the server into the data variable. And that wraps up this tip, which will help you return objects directly converted into JSON using Spring MVC.

Safari Books Online has the content you need

Here are some Spring books from Safari Books Online that you can enjoy as a Safari Books Online subscriber. If you are not a subscriber, you can take a test drive with a free Safari Books Online trial.

Totally revised for Spring 3.0, Spring in Action, Third Edition is a hands-on guide to the Spring Framework. It covers the latest features, tools, and practices including Spring MVC, REST, Security, Web Flow, and more.
The release of Spring Framework 3 has ushered in many improvements and new features. Spring Recipes: A Problem-Solution Approach, Second Edition continues upon the bestselling success of the previous edition but focuses on the latest Spring 3 features for building enterprise Java applications.
Spring Batch in Action is an in-depth guide to writing batch applications using Spring Batch. Written for developers who have basic knowledge of Java and the Spring lightweight container, the book provides both a best-practices approach to writing batch jobs and comprehensive coverage of the Spring Batch framework.
Spring Web Services 2 Cookbook includes a wide variety of recipes that covers most important topics used in real-world applications. It is a well-rounded guide covering a lot of ground in the Spring Web Services domain using systematic arranged chapters and focused recipes.

FREE 10-day trial.

About this author

Sebastiano Armeli-Battana is software engineer focused on JavaScript and Java development and he is really passionate about Web technologies. He works as consultant in SMS Management & Technology adopting Java technologies and he also works as Web freelancer. He is the author of a jQuery plugin called JAIL and he maintains his personal site at http://www.sebastianoarmelibattana.com.

About Safari Books Online

Safari Books Online is an online learning library that provides access to thousands of technical, engineering, business, and digital media books and training videos. Get the latest information on topics like Windows 8, Android Development, iOS Development, Cloud Computing, HTML5, and so much more – sometimes even before the book is published or on bookshelves. Learn something new today with a free subscription to Safari Books Online.

One Response to Spring MVC Tip: Returning JSON from a Spring Controller

  1. Alex says:

    Have you found a good way to conditionally return a view or JSON? That is, similar to other MVC frameworks that check X-Requested-With header to determine is_xhr true|false.