Spring Web MVC – Return JSON in Response Body

In this tutorial, you will learn how to use the @ResponseBody annotation to return JSON in the HTTP response body. You might also be interested to learn how to Read JSON Request Body in the Spring MVC Web application.

@ResponseBody Annotation

To make a method in the Controller class return JSON in HTTP Response body we use @ResponseBody annotation. This annotation will tell Spring Framework, that the object returned from this method, should be serialized into JSON and returned in the HTTP response body.

Below is an example of a method that handles HTTP Post requests. Notice that this method is annotated with @ResponseBody annotation.

@PostMapping(path="/users")
@ResponseBody
public ResponseEntity createUser(@RequestBody User user) {
    return new ResponseEntity(
            new UserRest(UUID.randomUUID().toString(),
                    user.getFirstName(),
                    user.getLastName(),
                    user.getEmail()
                    )
            ,HttpStatus.OK);
}

Method Return Value

Notice that the code snippet above returns an instance of the UserRest object, wrapped into ResponseEntity. ResponseEntity allows us to return HTTP Response with response body and custom HTTP Status Code. In the code example above, the HTTP status code is set to 200. But if needed you can set a different status code.

It is worth mentioning that, the UserRest class is a custom class that you can create. It is a class that needs to be serialized into JSON and returned in HTTP Response Body. An example of UserRest class is below.

public class UserRest {
    private final String id;
    private final String firstName;
    private final String lastName;
    private final String email;

    public UserRest(String id, String firstName, String lastName, String email) {
        this.id = id;
        this.firstName = firstName;
        this.lastName = lastName;
        this.email = email;
    }

    public String getId() {
        return id;
    }

    public String getFirstName() {
        return firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public String getEmail() {
        return email;
    }
}

I hope, this tutorial was helpful to you. To learn more about building Web applications with Spring Framework, please visit the Spring Web MVC category.

Happy learning!