Sub topic 7
Accepting JSON with @RequestBody
This chapter explains how Spring MVC turns a JSON request body into a Java object. It also covers what happens when the body is wrong. It assumes you can write a @RestController with @PostMapping, you know what a record is, and you know the HTTP basics: Content-Type, 400, and 415. Bean Validation has its own chapter, so @Valid appears here only as a pointer.
What @RequestBody does
A path variable or query parameter is a short string that Spring converts to a number or a string. A request body is different. It is a stream of bytes with a media type, and it can hold a whole object graph. When you annotate a method parameter with @RequestBody, you tell Spring to read that stream and convert it into the parameter's type.
Spring MVC does the conversion with HttpMessageConverter implementations. A converter declares which media types and Java types it supports. For application/json, Spring Boot registers a Jackson-based converter. It does this automatically when spring-boot-starter-web is on the classpath, because that starter brings in Jackson.
The steps for each request are:
- Spring picks the controller method from the URL and HTTP method.
- It reads the request's
Content-Typeheader. - It looks for a converter that can read that media type into the declared parameter type.
- The converter parses the bytes, and Jackson builds the object.
- Spring calls your method with the object.
A minimal example
This controller accepts a JSON body and returns the created resource. It is the plain form of the create endpoint shown in the topic's examples. The ResponseEntity version with Location comes in the next chapter.
import java.util.List;
import org.springframework.web.bind.annotation.*;
public record CreateBookRequest(String title, String author) {}
public record BookResponse(long id, String title, String author) {}
@RestController
@RequestMapping("/api/books")
public class BookController {
private final BookService service;
public BookController(BookService service) {
this.service = service;
}
@PostMapping
public BookResponse create(@RequestBody CreateBookRequest request) {
return service.create(request);
}
}You can call it with curl. The Content-Type header is required, and the next section explains why.
curl -i -X POST http://localhost:8080/api/books \
-H "Content-Type: application/json" \
-d '{"title":"Dune","author":"Frank Herbert"}'Jackson matches JSON property names to the record's component names. Records work without extra configuration in current Spring Boot versions, because Jackson 2.12 and later supports them. A class with a constructor works too if it is compiled with the -parameters flag, which Spring Boot's Maven and Gradle plugins enable. A mutable class with getters and setters also works.
The Content-Type header decides everything
The converter is chosen from the request's Content-Type, not from the body. A request that sends valid JSON with Content-Type: text/plain gets a 415 Unsupported Media Type response. A missing Content-Type header usually gets the same result.
You can restrict a method to certain media types with the consumes attribute:
@PostMapping(consumes = "application/json")
public BookResponse create(@RequestBody CreateBookRequest request) {
return service.create(request);
}Without consumes, the method still runs only when a converter can read the request's type into your parameter. The attribute makes the contract explicit. It also lets you register two methods for the same path, each handling a different input type.
What happens when the body is wrong
Spring turns several input problems into client errors before your method runs. Knowing which exception maps to which status helps when you build the global handler later.
| Situation | Exception | Default status |
|---|---|---|
| Body is not valid JSON | `HttpMessageNotReadableException` | 400 |
| A field has the wrong type, such as a string where a number is expected | `HttpMessageNotReadableException` | 400 |
| Body is missing and the parameter is required | `HttpMessageNotReadableException` | 400 |
| Unsupported `Content-Type` | `HttpMediaTypeNotSupportedException` | 415 |
| Constraint violation after `@Valid` | `MethodArgumentNotValidException` | 400 |
The default error body is not very informative. With spring.mvc.problemdetails.enabled=true, Spring MVC returns a ProblemDetail for these built-in exceptions. The error-handling chapter covers how to shape those responses.
Missing, extra, and null fields
Binding is lenient by default, and this surprises many developers.
Missing fields are not an error. A missing String or other object field becomes null. A missing primitive such as int or long becomes 0, and a missing boolean becomes false. If the difference between "absent" and "zero" matters, use wrapper types like Integer and Long in the DTO.
Unknown fields are ignored. Spring Boot configures its ObjectMapper with FAIL_ON_UNKNOWN_PROPERTIES disabled. A client that sends "titel" instead of "title" gets no error. The title value is simply null. To reject unknown properties across the whole application, set this property:
spring.jackson.deserialization.fail-on-unknown-properties=trueExplicit nulls are accepted. {"title": null} produces the same null as omitting the field. Plain Jackson cannot tell the two apart. That matters for partial updates, where you need to know whether a client wants to clear a field. If you need that distinction, you need a more elaborate design, such as JSON Merge Patch or a wrapper type.
The next chapter on validation covers rejecting null and blank values with @NotBlank. Binding alone never enforces that a field is present.
Naming and shaping the JSON
Use Jackson annotations on the DTO when the JSON contract differs from your Java names.
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
@JsonIgnoreProperties(ignoreUnknown = false)
public record BookImportRequest(
String title,
String author,
@JsonProperty("published_year") Integer publishedYear) {}@JsonProperty maps the JSON name published_year to the component publishedYear. @JsonIgnoreProperties(ignoreUnknown = false) makes this one class strict, even though the application default is lenient. To change naming for every DTO, use spring.jackson.property-naming-strategy=SNAKE_CASE instead of annotating each field.
Dates need no extra setup. spring-boot-starter-json includes the java.time module, so LocalDate and Instant bind from ISO-8601 strings such as "2024-05-17". Spring Boot also disables writing dates as numeric timestamps by default.
Collections and generics
You can bind a JSON array directly to a generic collection:
@PostMapping("/batch")
public List<BookResponse> createAll(@RequestBody List<CreateBookRequest> requests) {
return requests.stream().map(service::create).toList();
}This works because Spring reads the generic type from the method signature. Jackson sees List<CreateBookRequest>, not a raw List, so it builds CreateBookRequest objects instead of maps. Because a body can be large, consider limiting batch size in the service. A request with 100,000 elements is read fully into memory before your method starts.
Optional and single-use bodies
By default @RequestBody is required. An empty body produces a 400. To allow an empty body, set required = false, and the parameter will be null:
@PostMapping("/refresh")
public void refresh(@RequestBody(required = false) RefreshOptions options) {
service.refresh(options == null ? RefreshOptions.defaults() : options);
}A method can have only one @RequestBody parameter, because the request stream can be read once. If you need data from several places, combine a body with @PathVariable and @RequestParam parameters. Do not try to read the body twice, for example by also injecting HttpServletRequest and calling getInputStream(). The stream will already be consumed.
Design guidance
- Bind to DTOs, not entities. If you bind a request to a JPA entity, a client can set any field the entity exposes, such as
id,role, orcreatedAt. This is called mass assignment. A DTO lists exactly the fields you accept. - Use separate request and response types.
CreateBookRequesthas noid, andBookResponsehas no write-only fields. Sharing one class makes both contracts worse. - Keep DTOs immutable. Records give you this for free, and the object a controller receives cannot change under a service.
- Do not log raw bodies carelessly. Request bodies can contain passwords or personal data.
Common mistakes
- Forgetting
-H "Content-Type: application/json"in manual tests and getting a415. - Leaving off
@RequestBody. Spring then treats a complex parameter as a form-style model attribute, so the JSON is ignored and every field staysnull. - Using primitives in DTOs and not noticing that a missing number turned into
0. - Assuming a typo in a property name will cause an error.
Exercise
A client sends {"title":"Dune","autor":"Frank Herbert"} to POST /api/books, where CreateBookRequest is a record with title and author. The request has Content-Type: application/json, and you have changed no Jackson settings. What does the controller method receive, and what must you change so the request is rejected with a 400?
Show answer
The method receives a CreateBookRequest with title set to "Dune" and author set to null. Spring Boot ignores the unknown autor property by default, and a missing field becomes null. To reject the request, set spring.jackson.deserialization.fail-on-unknown-properties=true. Alternatively, put @JsonIgnoreProperties(ignoreUnknown = false) on the record. You could also add @NotBlank on author and use @Valid, which rejects the missing value instead of the unknown name.
Exercise
Why does curl -X POST -d '{"title":"Dune","author":"Frank Herbert"}' http://localhost:8080/api/books return a 415 even though the JSON is valid?
Show answer
curl sends form-encoded data by default, so the Content-Type is application/x-www-form-urlencoded. The Jackson converter cannot read that media type into the DTO. Add -H "Content-Type: application/json" to fix it.