Sub topic 7
Mapping JSON to records and DTOs with Jackson
This chapter assumes you have read the previous chapter on @RequestBody. You should know basic Java records and the JSON syntax. Here you will see how Jackson turns a JSON body into the object your handler receives, and where that conversion goes wrong.
What Jackson does for you
Spring Boot's web starter includes Jackson, a library that reads and writes JSON. When a handler parameter has @RequestBody, Spring picks a message converter based on the request's Content-Type header. For application/json it uses Jackson's ObjectMapper to build an instance of the parameter's type.
Use a DTO, not your entity
A DTO (data transfer object) is a class that describes only the data a request may carry. Keeping it separate from your database entity means a client cannot set fields such as id or createdAt. Records suit DTOs well: they are immutable and have a canonical constructor. Jackson 2.12 and later, which Spring Boot 2.5 and later include, binds JSON properties to record components by name.
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Positive;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.time.LocalDate;
public record CreateBookRequest(
@NotBlank String title,
@NotBlank String author,
@NotNull @Positive Integer pages,
@JsonProperty("published_on") LocalDate publishedOn) {}On Spring Boot 2.x, replace jakarta.validation with javax.validation.
This record accepts the following body:
curl -X POST http://localhost:8080/api/books \
-H "Content-Type: application/json" \
-d '{"title":"The Dispossessed","author":"Ursula K. Le Guin","pages":341,"published_on":"1974-05-01"}'Three details matter here:
- Property names match component names exactly, including case.
pagesbinds topages. @JsonProperty("published_on")maps a differently named JSON key to a component. To apply a naming style everywhere, setspring.jackson.property-naming-strategy=SNAKE_CASEinstead.LocalDateparses ISO strings such as1974-05-01. Boot registers Jackson's Java time module for you, and it writes dates as ISO strings rather than numeric arrays.
Defaults that surprise people
Spring Boot configures Jackson differently from plain Jackson. These behaviors cause most confusion:
| Situation | What happens | What to do |
|---|---|---|
| JSON has an extra, unknown key | Ignored. Boot turns off `FAIL_ON_UNKNOWN_PROPERTIES`. | Set `spring.jackson.deserialization.fail-on-unknown-properties=true` to reject it. |
| A key is missing | Reference types get `null`. A primitive `int` gets `0`. | Use wrapper types with `@NotNull`, as `pages` does above. |
| A key is present with the wrong type, such as `"pages":"many"` | `HttpMessageNotReadableException`, which gives a 400. | Handle it in an advice class. |
| Invalid JSON syntax | The same exception and a 400. | Same as above. |
| No `Content-Type: application/json` header | 415 Unsupported Media Type. | Fix the client. |
Customizing a single class
You can adjust binding per class without changing global settings. @JsonIgnoreProperties(ignoreUnknown = false) makes one DTO strict. @JsonFormat(pattern = "dd/MM/yyyy") on a component changes how that one date is parsed.
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import java.time.LocalDate;
@JsonIgnoreProperties(ignoreUnknown = false)
public record ReleaseRequest(
String title,
@JsonFormat(pattern = "dd/MM/yyyy") LocalDate releaseDate) {}Debugging checklist
- Read the response body and the server log. The message names the field and the expected type.
- Confirm the
Content-Typeheader on the request. - Compare JSON key spelling with the component names.
- Check whether a primitive is hiding a missing value.
Exercise
A client sends {"title":"Dune","author":"Frank Herbert","page_count":412} to an endpoint that takes CreateBookRequest (with a pages component of type Integer annotated @NotNull). With Spring Boot defaults, what response does it get, and why?
Show answer
A 400 response. Jackson ignores the unknown key pagecount, so the pages component is null. Bean Validation then rejects the null value with the @NotNull constraint. Fix it by sending "pages" or by adding @JsonProperty("pagecount") to the component.