Spring MVC - JSON response with @ResponseBody annotation (Spring + JSON)

Updated for Spring 5+

In our previous discussion we came across "XML response with @ResponseBody annotation (Spring + XML)". Today we will see how to return a JSON response from a Spring MVC Controller. All we need to do is adding @ResponseBody annotation in front of controller and adding 'jackson-mapper-asl' dependency to the classpath. Let's see the functioning of @ResponseBody annotation and how it helps in returning an java object in JSON form.


Expected Output

Our objective for today's discussion is clear, we will try to return a Java Object and a list of java objects as JSON response to the browser. See screen shots below how this will look like:

Single Java object as JSON response(Student.java)



List of Java objects as xml response(List )



Return a Java object as JSON response from Spring MVC controller

To return an java object in JSON form from an spring objects requires two simple configurations:
1) Adding 'jackson-mapper-asl' dependency to the classpath
2) Add @ResponseBody annotation to the controller's method


1) Adding 'jackson-mapper-asl' dependency to the classpath

In a spring mvc project we need to add a 'jackson-mapper-asl' dependency to the pom.xml file, and object to json conversion is done bydefault.
		<!-- Jackson JSON Mapper -->
		<dependency>
			<groupId>org.codehaus.jackson</groupId>
			<artifactId>jackson-mapper-asl</artifactId>
			<version>${jackson.version}</version>
		</dependency>
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
			<version>${jackson.databind}</version>
		</dependency>
   

2) Add @ResponseBody annotation to the controller's method

\src\main\java\com\beingjavaguys\controller\DataController.java

Second thing we need to do is to use '@ResponseBody' annotation against the controller's method. This will make spring understand that method return value should be bound to the web response body.
package com.beingjavaguys.controller;  
  
import java.util.ArrayList;  
import java.util.List;  
import org.springframework.stereotype.Controller;  
import org.springframework.web.bind.annotation.RequestMapping;  
import org.springframework.web.bind.annotation.ResponseBody;  
  
import com.beingjavaguys.domain.Student;  
  
@Controller  
public class DataController {  
  
 @RequestMapping("student")  
 public @ResponseBody  
 Student getStudent() {  
  return new Student(23, "meghna", "Naidu", "meghna@gmail.com",  
    "8978767878");  
 }  
  
 @RequestMapping("studentlist")  
 public @ResponseBody  
 List<Student> getStudentList() {  
  List<Student> studentList = new ArrayList<Student>();  
  studentList.add(new Student(23, "Meghna", "Naidu", "meghna@gmail.com",  
    "8978767878"));  
  studentList.add(new Student(3, "Robert", "Parera", "robert@gmail.com",  
    "8978767878"));  
  studentList.add(new Student(93, "Andrew", "Strauss",  
    "andrew@gmail.com", "8978767878"));  
  studentList.add(new Student(239, "Eddy", "Knight", "knight@gmail.com",  
    "7978767878"));  
  
  return studentList;  
 }  
  
}  


That's all we need to know about @ResponseBody annotation and how to return JSON response from Spring Controller. Lets now add all other useful files to our project to make it working.

Dependencies required to return JSON response from Spring Controller.

pom.xml

   <project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.beingjavaguys.sample</groupId>
	<artifactId>SpringJsonOutput</artifactId>
	<packaging>war</packaging>
	<version>1.0-SNAPSHOT</version>
	<name>SpringJsonOutput Maven Webapp</name>
	<url>http://maven.apache.org</url>

	<properties>
		<spring.version>5.1.5.RELEASE</spring.version>
		<jdk.version>1.8</jdk.version>
		<jackson.version>1.9.13</jackson.version>
		<jackson.databind>2.9.8</jackson.databind>
	</properties>

	<dependencies>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<!-- Jackson JSON Mapper -->
		<dependency>
			<groupId>org.codehaus.jackson</groupId>
			<artifactId>jackson-mapper-asl</artifactId>
			<version>${jackson.version}</version>
		</dependency>
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
			<version>${jackson.databind}</version>
		</dependency>

	</dependencies>

	<build>
		<finalName>SampleSpringMaven</finalName>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-eclipse-plugin</artifactId>
				<version>2.9</version>
				<configuration>
					<downloadSources>true</downloadSources>
					<downloadJavadocs>false</downloadJavadocs>
					<wtpversion>2.0</wtpversion>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>2.3.2</version>
				<configuration>
					<source>${jdk.version}</source>
					<target>${jdk.version}</target>
				</configuration>
			</plugin>
		</plugins>
	</build>

</project>


Spring configuration file

src\main\webapp\WEB-INF\spring-servlet.xml

This is simple spring configuration file, we have added an entry for our controller's location. Dont forget to add '<mvc:annotation-driven />' this is very important for @ResponseBody annotation to work.
<?xml version="1.0" encoding="UTF-8"?>  
<beans xmlns="http://www.springframework.org/schema/beans"  
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"  
 xmlns:util="http://www.springframework.org/schema/util" xmlns:mvc="http://www.springframework.org/schema/mvc"  
 xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd  
  http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd  
  http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd  
  http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">  
  
 <context:component-scan base-package="com.beingjavaguys.controller" />  
 <mvc:annotation-driven />  
  
</beans>  


src\main\webapp\WEB-INF\web.xml

<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   
       http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"  
 version="2.5">  
  
 <display-name>Sample Spring Maven Project</display-name>  
  
 <servlet>  
  <servlet-name>spring</servlet-name>  
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
  <load-on-startup>1</load-on-startup>  
 </servlet>  
  
 <servlet-mapping>  
  <servlet-name>spring</servlet-name>  
  <url-pattern>*.xml</url-pattern>  
 </servlet-mapping>  
  
</web-app> 

This is all we have added all required files to the project, lets see the overall project structure at once now. Project Structure

If everything goes right and you have configured everything well, run the projct on server and hit following two URL's in the browser.
1)Java Object as JSON response : http://localhost:8080/SpringJsonOutput/student.json
2)Java object's list as JSON response: http://localhost:8080/SpringJsonOutput/studentlist.json


You can also download full example project from the link given below in BLUE STRIP. In upcoming blogs we will see more about Spring, Hibernate, Java and Other opensource technologies.

Download source code from: GitHub.