Labs ICT
⭐ Pro Login

Request Body

接收 JSON and other payloads.

2 min read | Spring Boot Tutorial
⭐

Want the full learning experience?

Get structured courses, certificates, projects, and instructor support with LabsICT Pro.

Explore Pro Courses

The @RequestBody Annotation

When a client sends data to your API — like creating a new user — the data arrives in the request body. The @RequestBody annotation tells Spring to deserialize that body into a Java object.

Spring uses Jackson under the hood to map JSON fields to your object's properties. You define a class with the right fields, and Spring handles the conversion. No manual parsing, no boilerplate code.

JSON to Java Object Mapping

Define a POJO that matches the structure of the JSON your client sends. Spring maps the JSON keys to the object's fields automatically.

public class CreateUserRequest {
    private String name;
    private String email;
    private int age;

    getters and setters
}

@PostMapping("/users")
public User createUser(@RequestBody CreateUserRequest request) {
    User user = new User(request.getName(), request.getEmail());
    return userService.save(user);
}

A JSON body like {"name": "Alice", "email": "alice@example.com", "age": 30} gets converted to a CreateUserRequest instance.

@RequestBody with Validation

You can combine @RequestBody with validation annotations to enforce constraints on incoming data. Add @Valid before the parameter, and annotate your fields with constraints like @NotBlank or @Email.

If validation fails, Spring automatically returns a 400 Bad Request response with details about what went wrong. This keeps your controllers clean and your API consistent.

Handling Different Content Types

@RequestBody works with any content type that Jackson supports — not just JSON. It can handle XML, YAML, and other formats. Spring determines the format from the Content-Type header.

In practice, JSON is the most common choice. But if your clients need XML support, just add the jackson-dataformat-xml dependency and annotate your endpoint with consumes = MediaType.APPLICATION_XML_VALUE.

🧪 Quick Quiz

What is @RequestBody used for?