HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Spring REST / JSON Example

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 !!

Share this:

  • Twitter
  • Facebook
  • LinkedIn
  • Reddit

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Feedback, Discussion and Comments

  1. Akshay

    November 16, 2019

    I am getting response as string “jsonTemplate”

  2. lalit

    October 25, 2018

    i am getting an error

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

  3. Abhinay jain

    July 20, 2018

    My debugger is not coming from js file to java controller please help me

  4. abhay

    April 13, 2018

    How can we show above employee response in html page?

  5. sandeep

    October 3, 2016

    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’.

  6. rajesh

    August 30, 2016

    Hi Lokesh
    still i am getting the string “jsonTmeplate” instead of that json.
    I am passing the json-value in header too.

    • Trupti

      July 16, 2019

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

  7. rajesh

    August 30, 2016

    I am still getting the output as jsontemplate instead of passing the json value in header.

  8. Daal

    May 15, 2016

    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

  9. Shashi Shekhar

    February 15, 2016

    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

    • Lokesh Gupta

      February 16, 2016

      Doesn’t sound version issue to me. It’s probably @RequestMapping issue. Try appending or removing “/”. Otherwise please share the method signature you are using.

      • Shashi Shekhar

        February 16, 2016

        @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);
        }

      • Shashi Shekhar

        February 16, 2016

        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”

        • Lokesh Gupta

          February 16, 2016

          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.

          • Shashi Shekhar

            February 16, 2016

            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.

            • Ajai

              December 22, 2017

              Are u having jackson 2.1.2 in your lib

  10. Partha Sarkar

    December 18, 2015

    Look at the xml returned by the web service it is employees under employees . is it right. how should I changed it ?

    • Lokesh Gupta

      December 21, 2015

      Try changing JAXB annotations in Employees.java class.

  11. Gaurav

    December 18, 2015

    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

  12. Nash

    October 16, 2015

       @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.

    • Lokesh Gupta

      October 16, 2015

      Are you passing “accept: application/json” HTTP header?

  13. Smail

    July 21, 2015

    Hi,

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

  14. rinilnath

    July 16, 2015

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

    • Lokesh Gupta

      July 16, 2015

      If you will configure the project with information present in this post, you will get similar response.

    • Chirag

      October 10, 2015

      Same here. It shows only word jsonTemplate

  15. Sharat

    May 12, 2015

    Getting JSon response with empty values. Sample attached:

    {“employees”:{“employees”:[{},{},{}]}}

    • Lokesh Gupta

      May 13, 2015

      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;;
          }
      }
      
    • Kartik

      July 7, 2015

      Yes, Getting the same response.

      • Kartik

        July 7, 2015

        {“employees”:{“employees”:[{},{},{}]}}

        • Lokesh Gupta

          July 7, 2015

          Make sure you are returning some data first. and have proper setter and getter methods as well.

          • Kartik

            July 7, 2015

            I have implemented same class which you have given in https://howtodoinjava.com/spring-rest/spring-rest-hello-world-xml-example/

            • Kartik

              July 7, 2015

              Done..Getter setter were missing.

              • Lokesh Gupta

                July 7, 2015

                Great !!

  16. Binh Thanh Nguyen

    March 6, 2015

    Thanks, nice share

Comments are closed on this article!

Search Tutorials

Spring REST Tutorials

  • Spring REST – JSON
  • Spring REST – XML
  • Spring REST – Controller
  • Spring REST – CRUD App
  • Spring REST – Exception Handler
  • Spring REST – Request Validation
  • Spring REST – Custom Token Auth
  • Spring REST – Multipart
  • Spring REST – Multiple uploads
  • Spring REST – OPTIONS Handler
  • Spring REST – Access denied JSON
  • Spring REST – RestTemplate

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Java 15 New Features
  • Sealed Classes and Interfaces
  • EdDSA (Ed25519 / Ed448)