Spring REST JSON Response Example

Lokesh Gupta

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

Comments

Subscribe
Notify of
guest
9 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode