Saturday, April 18, 2020

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.

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

pom.xml
<!-- 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
EmployeeRESTController.java
@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

pom.xml
  <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.
RESTConfiguration.java
@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.
spring-servlet.xml
 
    <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.

No comments:

Post a Comment

How to DROP SEQUENCE in Oracle?

  Oracle  DROP SEQUENCE   overview The  DROP SEQUENCE  the statement allows you to remove a sequence from the database. Here is the basic sy...