Spring REST JSON Response Example

In Spring REST JSON example, we will learn to create REST APIs capable of returning JSON representations of the resources. We will use the following methods for configuring the JSON responses:

  • @ResponseBody Annaotion
  • MappingJackson2JsonView view resolver

Read Spring REST XML tutorial if you want to return the XML representations as well.

1. Spring REST JSON with @ResponseBody

This first technique is simple and easy. We have to include only Jackson dependencies into the classpath of the application, and Spring will register Jackson2JsonMessageConverter bean automatically into context.

When we return a response from a REST API, Jackson2JsonMessageConverter will convert the Java object into a JSON string, and we will get back the JSON representation of the resource on the client-side.

1.1. Maven and Gradle Dependencies

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.13.0</version>
</dependency>
implementation 'com.fasterxml.jackson.core:jackson-databind:2.13.0'

1.2. @ResponseBody Annotation

The @ResponseBody annotation tells the controller that the object returned is automatically serialized into JSON and passed back into the HttpResponse object.

Remember that @ResponseBody is part of @RestController annotation, so we do not need to apply it explicitly. Read more for a detailed discussion.

@RestController
public class EmployeeRESTController
{
    @GetMapping(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;
    }
      
    @GetMapping(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 with MappingJackson2JsonView Support

The MappingJackson2JsonView bean also depends on the presence of the Jackson JSON processor library in classpath, which we have already seen in the first section. So you don’t need to add anything extra dependency. pom.xml looks like this.

2.1. Adding MappingJackson2JsonView

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

2.2.1. Controller Changes

  • You will need to configure the viewName from the controller method. In our case, the view name is “jsonTemplate“.
  • Also, do not forget to add the response data into Model.
  • Similarily, you need to return the string jsonTemplate from the all the methods in controller classes when you want to return a JSON response.
@RestController
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;
	}

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

2.2.2. Configuration Changes

we will need to configure viewName “jsonTemplate” as a bean of type MappingJackson2JsonView. And we will need to configure the view resolver of type BeanNameViewResolver.

This way viewName “jsonTemplate” will be matched with MappingJackson2JsonView, and Spring will return parsed JSON response to the 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();
    }
}

The equivalent XML configuration to the 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. Demo

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

Spring REST JSON Example
Spring REST JSON Example

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

Happy Learning !!

Was this post helpful?

Join 7000+ Awesome Developers

Get the latest updates from industry, awesome resources, blog updates and much more.

* We do not spam !!

9 thoughts on “Spring REST JSON Response Example”

  1. 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
      • 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
      • @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
  2.    @RequestMapping(value = "/employees")
        public String getAllEmployeesJSON(Model model)
        {
            model.addAttribute("employees", getEmployeesCollection());
            return "jsonTemplate";
        }
    
    thanks for the tutorial. In the above condition, in my case, "jsonTemplate" is behaving like a string even after the execution. My output is string "jsonTemplate" although 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
  3. 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

Leave a Comment

HowToDoInJava

A blog about Java and related technologies, the best practices, algorithms, and interview questions.