Read JSON Request Body in Spring Web MVC

In previous, video tutorials I have shared with you how to read Request Path parameters, Query String parameters and Form data. In this tutorial, you will learn how to make a method in the Controller class read JSON body from HTTP request.

To read the body of HTTP request, we will use the @RequestBody annotation that Spring Web MVC framework provides.

 @RequestBody Annotation

To read the body of HTTP request and map it to a Java object right away, we use @RequestBody annotation.

@PostMapping(path="/users")
public ResponseEntity createUser(@RequestBody User user) {
    return ResponseEntity.ok(HttpStatus.OK);
}

When we use the @RequestBody annotation, Spring Framework will read the content of HTTP body, and it will map it to the Java object used as method argument.

For Spring Framework to be able to map JSON key-value pairs to the properties in the User class. The user class will need to have property names, with exactly the same names, as we have in the JSON payload.

public class User {
    private String firstName;
    private String lastName;
    private String email;
    private String password;
    private String repeatPassword;

    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 String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getRepeatPassword() {
        return repeatPassword;
    }

    public void setRepeatPassword(String repeatPassword) {
        this.repeatPassword = repeatPassword;
    }
}

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