Thursday, January 28, 2021

Spring MVC JSON as Response Example

In this post we’ll see how to generate JSON as response in Spring MVC application.

Technologies used

Following is the list of tools used for the Spring MVC JSON generation example.

  • Spring 5.0.8 Release (Spring core, spring web, spring webmvc).
  • Java 10
  • Tomcat server V 9.0.10
  • Eclipse Photon 4.8.0 for Java EE development (This Eclipse version supports Java 10)
  • Jackson library (For JSON)

Spring MVC Project structure using Maven

Maven Dependencies

Apart from Spring framework dependencies you need to add the following dependency for JSON.

<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-databind</artifactId>
  <version>2.9.6</version>
</dependency>

Which adds the following jars.

jackson-databind-2.9.6.jar
jackson-annotations-2.9.0.jar
jackson-core-2.9.6.jar

Requirement for generating JSON in Spring MVC

In order to return JSON as response with in your Spring MVC application-

  1. You need to add JSON related jars to the class path.
  2. @ResponseBody annotation has to be added to the controller's method, with that returned value is serialized to the response body through an HttpMessageConverter.

Spring MVC JSON as response – Model classes

There are two classes User class whose objects are returned in the JSON format and UserListContainer class which contains the List of objects of type User, this class is needed as we are sending a list of Users.

public class User {

 private String firstName;
 private String lastName;
 private String email;

 public User() {
  
 }
 public User(String firstName, String lastName, String email) {
  this.firstName = firstName;
  this.lastName = lastName;
  this.email = email;
 }
 
 public String getFirstName() {
  return firstName;
 }
 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }
 public String getLastName() {
  return lastName;
 }
 public void setLastName(String lastName) {
  this.lastName = lastName;
 }
 public String getEmail() {
  return email;
 }
 public void setEmail(String email) {
  this.email = email;
 }
}
public class UserListContainer {
  private List<User> userList;
  public List<User> getUserList() {
    return userList;
  }
  public void setUserList(List<User> userList) {
    this.userList = userList;
  }
}

Spring MVC JSON as response – Controller classes

@Controller
public class UserController {
  @RequestMapping(value = "/getUsers", method = RequestMethod.GET, produces="application/json")
  @ResponseBody
  public UserListContainer getUsers(Model model) throws Exception{
    List<User> users = getListOfUsers();
    UserListContainer userList = new UserListContainer();
    userList.setUserList(users);
    return userList;
  }
    
  // Dummy method for adding List of Users
  private List<User> getListOfUsers() throws ParseException {
    List<User> users = new ArrayList<User>();
    users.add(new User("Jack", "Reacher", "abc@xyz.com"));
    users.add(new User("Remington", "Steele", "rs@cbd.com"));
    users.add(new User("Jonathan", "Raven", "jr@sn.com"));
    return users;
  }
}

Here in the handler method you can see a new attribute “produces” with value as “application/json” with in the @RequestMapping annotation to explicitly specify that response will be send back to the client in JSON format.

@ResponseBody annotation is also used in the handler method to indicate that the returned object has to be serialized to the response body. Note that return is serialized to the response body through an HttpMessageConverter.

Deploying and testing application

Once the application is deployed to Tomcat server it can be accessed using the URL- http://localhost:8080/spring-mvc/getUsers and JSON will be returned as response.

Spring MVC generate JSON

That's all for this topic Spring MVC JSON as Response Example. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Spring Tutorial Page


Related Topics

  1. Spring MVC PDF Generation Example
  2. Spring MVC File Download Example
  3. Difference Between @Controller And @RestController Annotations in Spring
  4. Spring MVC Exception Handling Tutorial
  5. Spring MVC @RequestParam Annotation Example

You may also like-

  1. Transaction Management in Spring
  2. Data Access in Spring Framework
  3. Spring Bean Life Cycle
  4. @Resource Annotation in Spring Autowiring
  5. How to Sort HashSet in Java
  6. Java ArrayBlockingQueue With Examples
  7. Difference Between throw And throws in Java
  8. What is Big Data

No comments:

Post a Comment