Spring REST JSON Response Example

In Spring REST JSON example, we will learn to write RESTful webservices capable of returning JSON representations of resources. We will use MappingJackson2JsonView to resolve views to JSON body.

Read More: Spring REST XML tutorial

1. Spring REST JSON – @ResponseBody Annotation

This first technique is simple and easy. We have to include only jackson dependencies into classpath of the application and spring will register Jackson2JsonMessageConverter class automatically into context. Whenever we ask for a resource from REST API and provide http header “accept: application/json“, we will get back the json representation of resource.

1.1. Runtime JSON dependency

<!-- Jackson JSON Processor -->
<dependency>
	<groupId>com.fasterxml.jackson.core</groupId>
	<artifactId>jackson-databind</artifactId>
	<version>2.4.1</version>
</dependency>

1.2. @ResponseBody Support

Here @RestController = @Controller + @ResponseBody

@RestController
public class EmployeeRESTController
{
    @RequestMapping(value = "/employees")
    public EmployeeListVO getAllEmployees()
    {
        EmployeeListVO employees = new EmployeeListVO();
         
        EmployeeVO empOne = new EmployeeVO(1,"Lokesh","Gupta","howtodoinjava@gmail.com");
        EmployeeVO empTwo = new EmployeeVO(2,"Amit","Singhal","asinghal@yahoo.com");
        EmployeeVO empThree = new EmployeeVO(3,"Kirti","Mishra","kmishra@gmail.com");
         
         
        employees.getEmployees().add(empOne);
        employees.getEmployees().add(empTwo);
        employees.getEmployees().add(empThree);
         
        return employees;
    }
     
    @RequestMapping(value = "/employees/{id}")
    public ResponseEntity<EmployeeVO> getEmployeeById (@PathVariable("id") int id)
    {
        if (id <= 3) {
            EmployeeVO employee = new EmployeeVO(1,"Lokesh","Gupta","howtodoinjava@gmail.com");
            return new ResponseEntity<EmployeeVO>(employee, HttpStatus.OK);
        }
        return new ResponseEntity(HttpStatus.NOT_FOUND);
    }
}

2. Spring REST JSON – MappingJackson2JsonView Support

This is second technique. The MappingJackson2JsonView class also depends on the presence of the Jackson JSON processor library in classpath, so you don’t need to add anything extra. Complete pom.xml looks like this.

2.1. Maven dependencies

<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.howtodoinjava.demo</groupId>
  <artifactId>springrestexample</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>springrestexample Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>
    
    <!-- Spring MVC support -->
    
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-webmvc</artifactId>
		<version>4.1.4.RELEASE</version>
	</dependency>

	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-web</artifactId>
		<version>4.1.4.RELEASE</version>
	</dependency>
	
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-core</artifactId>
		<version>4.1.4.RELEASE</version>
	</dependency>
	
	<!-- Jackson JSON Processor -->
	<dependency>
		<groupId>com.fasterxml.jackson.core</groupId>
		<artifactId>jackson-databind</artifactId>
		<version>2.4.1</version>
	</dependency>
			
  </dependencies>
  <build>
    <finalName>springrestexample</finalName>
  </build>
</project>

2.2. Add MappingJackson2JsonView view

When you are using MappingJackson2JsonView class, you will need to return a view name of type MappingJackson2JsonView. So you will need to change two places.

2.2.1. Controller change

You will need to return viewName from controller method. In our case, view name is “jsonTemplate“.

package com.howtodoinjava.demo.controller;

import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.howtodoinjava.demo.model.EmployeeListVO;
import com.howtodoinjava.demo.model.EmployeeVO;

@Controller
public class EmployeeRESTController 
{
	
	private EmployeeListVO getEmployeesCollection()
	{
		EmployeeListVO employees = new EmployeeListVO();
		
		EmployeeVO empOne = new EmployeeVO(1,"Lokesh","Gupta","howtodoinjava@gmail.com");
		EmployeeVO empTwo = new EmployeeVO(2,"Amit","Singhal","asinghal@yahoo.com");
		EmployeeVO empThree = new EmployeeVO(3,"Kirti","Mishra","kmishra@gmail.com");
		
		
		employees.getEmployees().add(empOne);
		employees.getEmployees().add(empTwo);
		employees.getEmployees().add(empThree);
		
		return employees;
	}
	
	@RequestMapping(value = "/employees")
	public String getAllEmployeesJSON(Model model) 
	{
		model.addAttribute("employees", getEmployeesCollection());
	    return "jsonTemplate";
	}
}
2.2.2. Configuration Change

You will need to configure viewName “jsonTemplate” as bean of type MappingJackson2JsonView. And you will need to configure view resolver of type BeanNameViewResolver. This way viewName “jsonTemplate” will be matched with MappingJackson2JsonView and parsed JSON response will be returned to client.

@Configuration
public class RESTConfiguration 
{
    @Bean
    public View jsonTemplate() {
        MappingJackson2JsonView view = new MappingJackson2JsonView();
        view.setPrettyPrint(true);
        return view;
    }
	
    @Bean
    public ViewResolver viewResolver() {
        return new BeanNameViewResolver();
    }
}

Equivalent XML configuration to above java configuration is as below.

<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:mvc="http://www.springframework.org/schema/mvc" 
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context/ http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/mvc/ http://www.springframework.org/schema/mvc/spring-mvc.xsd">

	<context:component-scan base-package="com.howtodoinjava.demo" />
	<mvc:annotation-driven />
	
	<!-- JSON Support -->
	<bean name="viewResolver" class="org.springframework.web.servlet.view.BeanNameViewResolver"/>
	<bean name="jsonTemplate" class="org.springframework.web.servlet.view.json.MappingJackson2JsonView"/>

</beans>

3. Spring REST JSON example – Demo

Now when you hit the URL : http://localhost:8080/springrestexample/employees , you will get this result.

Spring REST JSON Example
Spring REST JSON Example

4. Spring REST JSON example – Project Structure

Spring REST JSON Example - Project Structure
Spring REST JSON Example – Project Structure

That’s all for this quick spring restful web services json example with spring mvc. Drop me your questions in comments.

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

34 thoughts on “Spring REST JSON Response Example”

  1. i am getting an error

    The type org.springframework.context.annotation.ScopedProxyMode cannot be resolved. It is indirectly referenced from required .class files

    Reply
  2. error:org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 9 in XML document from ServletContext resource [/WEB-INF/spring-servlet.xml] is invalid; nested exception is org.xml.sax.SAXParseException; lineNumber: 9; columnNumber: 69; cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element ‘context:component-scan’.

    Reply
    • change your annotation from @RestController to @Controller it will work and add getter setter methods in EmployeeVo.java class

      Reply
  3. Thanks for nice article. I am getting following error:

    java.lang.NoSuchMethodError: org.springframework.web.servlet.view.json.MappingJackson2JsonView.setResponseContentType(Ljavax/servlet/http/HttpServletRequest;Ljavax/servlet/http/HttpServletResponse;)V

    Can you please help.

    Entries in classpath file

    Reply
  4. Hi Lokesh,

    when i try sending json as data in ajax call to spring request handler method it says “Request method ‘POST’ not supported” even though I have mentioned method type POST in server side as well as client side ajax call.

    it is a liferay environment and springframework. But same code is working on a separate spring app. I am not able to figure out what could be the problem.

    Can this problem be because of jackson-databinding jar version. If yes how could i know which version should i use with spring 4.1.4

    Reply
      • @RequestMapping(value = “/coa/listtype/calculator”, produces = “application/json;charset=UTF-8″, consumes=”application/json;charset=UTF-8”, method = RequestMethod.POST)
        public @ResponseBody String saveListCalcExpense(@RequestBody ListTypeCalculator listTypeCalculator){
        Result result;
        try{
        System.out.println(“DamageId >>>>>>>>>>”+listTypeCalculator.getDamageId());
        result = new Result(ResultStatus.SUCCESS, “save_calc_expense”, listTypeCalculator);
        }catch(Exception e){
        result = new Result(ResultStatus.ERROR, “save_calc_expense”, null);
        }
        return new Gson().toJson(result);
        }

        Reply
      • It is also saying browser console “NetworkError: 405 Method Not Allowed” and on server side it is saying “WARN org.springframework.web.servlet.PageNotFound::handleHttpRequestMethodNotSupported – Request method ‘POST’ not supported”

        Reply
        • It’s probably @requestmapping issue. Try removing “/” from value = “/coa/listtype/calculator”. Make it value = “coa/listtype/calculator”. Use consumes and produces=MediaType.APPLICATION_JSON_VALUE instead of application/json;charset=UTF-8.

          Reply
          • Even consumes and produces=MediaType.APPLICATION_JSON_VALUE didn’t work… 🙁 … I also tried removing “/” but didn’t the things working… same code is working on a separate project i have created just to test this. But didn’t get any breakthrough on the main project.

            Earlier I was using following jars

            org.codehaus.jackson
            jackson-core-asl
            1.9.13

            org.codehaus.jackson
            jackson-jaxrs
            1.9.13

            org.codehaus.jackson
            jackson-mapper-asl
            1.9.13

            Now I changed it to

            com.fasterxml.jackson.core
            jackson-databind
            2.4.1.3

            com.fasterxml.jackson.core
            jackson-annotations
            2.4.1

            Still having same issue.

  5. Hi,
    Used first approach but getting an below error. Could you please tell me that why I am getting this error.

    org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException

    Thanks,
    Gaurav

    Reply
  6.    @RequestMapping(value = "/employees")
        public String getAllEmployeesJSON(Model model)
        {
            model.addAttribute("employees", getEmployeesCollection());
            return "jsonTemplate";
        }
    

    thanks for tutorial. In above condition, in my case “jsonTemplate” is behaving like string even after the execution. My output is string “jsonTemplate” althought I think i have correctly configured Mappingjackson2Jasonview and BeanNameViewResolver. Could you please let me know what might be the possible cause for “jsonTemplate” not connecting to Mappingjackson2jasonview.

    Reply
  7. Hi,

    We can just use
    @RequestMapping(value = “/employees”, method = RequestMethod.GET ,produces=MediaType.APPLICATION_JSON_VALUE) without change compared to Spring REST XML tutorial

    Reply
  8. The resultant is invalid format of JSON. Not the one as shown in the image.
    So in chrome it shows only word jsonTemplate

    Reply
    • Is your EmployeeVO class different ??

      import java.io.Serializable;
      import javax.xml.bind.annotation.XmlAccessType;
      import javax.xml.bind.annotation.XmlAccessorType;
      import javax.xml.bind.annotation.XmlAttribute;
      import javax.xml.bind.annotation.XmlElement;
      import javax.xml.bind.annotation.XmlRootElement;
       
      @XmlRootElement (name = &quot;employee&quot;)
      @XmlAccessorType(XmlAccessType.NONE)
      public class EmployeeVO implements Serializable
      {
          private static final long serialVersionUID = 1L;
       
          @XmlAttribute
          private Integer id;
           
          @XmlElement
          private String firstName;
           
          @XmlElement
          private String lastName;
           
          @XmlElement
          private String email;
           
          public EmployeeVO(Integer id, String firstName, String lastName, String email) {
              super();
              this.id = id;
              this.firstName = firstName;
              this.lastName = lastName;
              this.email = email;
          }
           
          public EmployeeVO(){
               
          }
       
          //Setters and Getters
       
          @Override
          public String toString() {
              return &quot;EmployeeVO [id=&quot; + id + &quot;, firstName=&quot; + firstName
                      + &quot;, lastName=&quot; + lastName + &quot;, email=&quot; + email + &quot;]&quot;;
          }
      }
      
      Reply

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.