Sub topic 7
Mapping JSON to Records and DTOs with Jackson
This chapter covers how Spring turns a JSON request body into a Java object. It assumes you know basic Java, including records, and that you have a Spring Boot web project (spring-boot-starter-web) that runs. You should also know basic JSON syntax and HTTP status codes. The previous chapter showed @RequestBody on a handler parameter. Here the focus is what happens after Spring sees that annotation.
What Jackson does for you
Spring Boot includes Jackson, a library that reads and writes JSON. When a handler parameter has @RequestBody, Spring picks an HttpMessageConverter that supports the request's Content-Type. For application/json, that converter is backed by Jackson's ObjectMapper. The converter reads the body bytes, builds an object of the parameter's declared type, and passes it to your method.
The same converter works in the other direction. When a @RestController method returns an object, Jackson writes it as JSON in the response.
Both failure branches end before your method runs. If the handler executes, you hold a fully built object.
A request DTO as a record
A DTO (data transfer object) is a class whose only job is to carry data across a boundary. For request bodies, it describes the shape of what clients may send. A record fits well because it is immutable and has no boilerplate.
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Positive;
public record CreateBookRequest(
@NotBlank String title,
@NotBlank String author,
@Positive int pages) {}A handler that uses it:
@PostMapping
public ResponseEntity<Book> create(@Valid @RequestBody CreateBookRequest request) {
Book saved = service.create(request);
URI location = ServletUriComponentsBuilder.fromCurrentRequest()
.path("/{id}")
.buildAndExpand(saved.id())
.toUri();
return ResponseEntity.created(location).body(saved);
}This body matches the record:
curl -X POST http://localhost:8080/api/books \
-H "Content-Type: application/json" \
-d '{"title":"A Wizard of Earthsea","author":"Ursula K. Le Guin","pages":183}'Jackson matches JSON property names to the record's component names. It calls the record's canonical constructor with the values. Jackson 2.12 and later support records directly, and Spring Boot 3 ships a version well past that, so no extra annotations are needed.
Why a separate request type
You could bind directly to an entity such as Book. Avoid that for three reasons:
- A client could set fields it should not control, such as
idor an internal status flag. This is called mass assignment. - Validation rules for creating a book often differ from the rules that apply to a stored one.
- The API shape becomes tied to your database model, so a column rename breaks clients.
A request DTO states exactly which fields a client may send and nothing more.
Rules for matching names and types
Jackson applies a few rules that explain most surprises.
| Situation | Default behavior |
|---|---|
| JSON has a property the DTO lacks | Ignored. Spring Boot turns off Jackson's `FAIL_ON_UNKNOWN_PROPERTIES`. |
| DTO has a component the JSON lacks | Reference types become `null`. Primitives such as `int` become `0`. |
| JSON value has the wrong type, such as `"pages":"many"` | Fails and produces a 400 response. |
| JSON text is malformed | Fails and produces a 400 response. |
| JSON `null` for a primitive component | Becomes `0` (the default for `int`), because `FAIL_ON_NULL_FOR_PRIMITIVES` is off. |
| Property name case differs, such as `Title` | Does not match by default. Names are case-sensitive. |
The missing-property row matters for validation. If a client omits pages, the int component becomes 0, and @Positive rejects it. If you used Integer pages instead, the value would be null. @Positive treats null as valid, so you would also need @NotNull. Choose the type with that in mind.
Spring Boot also converts strings like "2024-05-01" into LocalDate when the JSON property is a date. That works because Spring Boot registers Jackson's jackson-datatype-jsr310 module and disables writing dates as numeric timestamps. In a JSON body, dates use ISO-8601 text by default. This differs from query parameters, where you need @DateTimeFormat (covered in the type conversion chapter).
Controlling property names and shape
Sometimes the JSON contract differs from your Java naming. Jackson annotations adjust the mapping without changing the code that uses the object.
import com.fasterxml.jackson.annotation.JsonAlias;
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.constraints.NotBlank;
public record CreateAuthorRequest(
@JsonProperty("full_name") @NotBlank String fullName,
@JsonAlias({"born", "birth_year"}) Integer birthYear) {}@JsonProperty("full_name")binds the JSON propertyfull_nameto the componentfullName. It also controls the name used when this record is written to JSON.@JsonAliasaccepts extra input names. It affects reading only. Output still uses the primary name.
For a project that uses snake_case everywhere, set a global naming strategy in application.properties instead of annotating each field:
spring.jackson.property-naming-strategy=SNAKE_CASEWith that setting, fullName maps to full_name automatically, for both reading and writing.
Rejecting unknown fields
Ignoring unknown properties is lenient. A client that misspells autor gets no error from Jackson. The author component becomes null, and @NotBlank catches it only if you added that annotation. To fail on unknown properties, set this property:
spring.jackson.deserialization.fail-on-unknown-properties=trueThe request then fails with a 400 response that names the unknown property. This helps catch typos. The cost is that older clients break if they send fields you removed, so decide per API.
Nested objects and collections
DTOs can contain other DTOs and collections. Jackson binds them recursively. Add @Valid on the nested component so Bean Validation descends into it.
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.Positive;
import java.util.List;
public record CreateShelfRequest(
@NotBlank String name,
@NotEmpty List<@Valid BookEntry> books) {
public record BookEntry(@NotBlank String title, @Positive int pages) {}
}curl -X POST http://localhost:8080/api/shelves \
-H "Content-Type: application/json" \
-d '{"name":"Fantasy","books":[{"title":"A Wizard of Earthsea","pages":183}]}'Without @Valid on the list element, a book with an empty title passes validation. Bean Validation does not look inside nested objects unless told to. Validation is covered fully in the next chapter. Here the point is only that binding and validation are separate steps. Jackson builds the whole object tree, and validation then inspects it.
Enums
Jackson binds an enum from the JSON string that matches a constant's name exactly.
public enum Genre { FANTASY, SCIENCE_FICTION, HISTORY }
public record UpdateGenreRequest(Genre genre) {}{"genre":"FANTASY"} works. {"genre":"fantasy"} fails with a 400 response, because matching is case-sensitive. To accept lowercase, enable case-insensitive enum handling:
spring.jackson.mapper.accept-case-insensitive-enums=trueAn unknown value such as "POETRY" always fails. The error message from Jackson lists the accepted constants, which is useful while debugging but may reveal more detail than you want in production. The error-handling chapter shows how to replace it with your own message.
Classes instead of records
Records are the default choice in modern Spring code. A regular class works too. Jackson needs a way to create it and to set its values. The usual options are:
- A no-argument constructor plus setters. Jackson creates an empty object and calls the setters.
- A constructor annotated with
@JsonCreatorand parameters annotated with@JsonProperty. - A single constructor with parameter names preserved. Spring Boot's build plugins compile with the
-parametersflag, so Jackson can read the names.
public class RenameRequest {
private String title;
public String getTitle() { return title; }
public void setTitle(String title) { this.title = title; }
}If the class has neither a default constructor nor a usable creator, Jackson cannot build it. The request then fails with a 400 response whose cause is a message like "Cannot construct instance". That message is the signal to add one of the options above.
Common errors
- Missing
Content-Typeheader. Withcurl -dalone, the header isapplication/x-www-form-urlencoded, not JSON. The server returns 415 Unsupported Media Type. Add-H "Content-Type: application/json". - Empty body.
@RequestBodyis required by default. A POST with no body fails with 400. Use@RequestBody(required = false)only if an empty body is meaningful, and handle thenullyourself. - Shell quoting. Single quotes around the JSON keep the shell from altering the double quotes. On Windows
cmd, use double quotes with escaped inner quotes. - Trailing commas and comments. Standard JSON forbids both, and Jackson rejects them by default.
- Numbers too large for the type.
"pages": 99999999999overflowsintand produces a 400 response. Uselongwhen values can exceed about 2.1 billion. - Date text that does not match the type.
"2024-5-1"is not valid ISO-8601 and fails. Use2024-05-01. - Assuming a bound object is valid. A successfully bound DTO can hold
nullor0for absent fields. Binding only checks shape. Validation checks meaning.
What a binding failure looks like
When Jackson cannot read the body, Spring throws HttpMessageNotReadableException. Spring Boot's default handling returns 400. To produce your own response, add an @ExceptionHandler for it in the @RestControllerAdvice class from the error-handling chapter:
import org.springframework.http.HttpStatus;
import org.springframework.http.ProblemDetail;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class JsonErrorHandler {
@ExceptionHandler(HttpMessageNotReadableException.class)
public ProblemDetail handleUnreadable(HttpMessageNotReadableException ex) {
return ProblemDetail.forStatusAndDetail(
HttpStatus.BAD_REQUEST, "Request body is missing or not valid JSON");
}
}This message is deliberately generic. Returning ex.getMessage() would expose class names and parser positions to clients.
Summary of decisions
- Bind request bodies to dedicated DTOs, not entities.
- Prefer records for immutable, short DTOs.
- Use
Integerwith@NotNullwhen you must tell "absent" from "zero". Useintwith@Positivewhen zero is also invalid. - Add
@JsonPropertyfor single names that differ, or a global naming strategy for a whole API. - Decide deliberately whether unknown properties should fail.
Exercise
A client posts {"title":"Dune","author":"Frank Herbert"} to an endpoint that takes CreateBookRequest, where pages is declared as @Positive int pages. The handler has @Valid on the parameter. What does the client receive, and what would change if pages were declared as @Positive Integer pages?
Show answer
With int pages, Jackson binds the missing property as 0, so @Positive fails and the client gets a 400 response from validation. With Integer pages, the missing property becomes null, and @Positive treats null as valid, so the request is accepted with pages set to null. Adding @NotNull would make it fail again.
Exercise
Your DTO is record CreateAuthorRequest(@JsonProperty("full_name") String fullName). A client sends {"fullName":"Ursula K. Le Guin"}. What value does fullName have in the handler, and why?
Show answer
It is null. @JsonProperty renames the expected JSON property to full_name, so fullName in the JSON is an unknown property. Spring Boot ignores unknown properties by default, so no error occurs and the component stays null.