Sub topic 3
How Jackson reads and writes records
This chapter assumes you know basic Java and records, can write a Spring Boot @RestController, and know how JSON request and response bodies work. Jackson is the JSON library that Spring Boot uses by default. It comes with spring-boot-starter-web, so you need no extra dependency.
Writing: from record to JSON
Jackson has supported records since version 2.12, and every current Spring Boot release includes a newer version. To write a record, Jackson calls the record's accessor methods. A record component name has an accessor called name(), not getName(). Jackson recognizes record accessors and uses the component name as the JSON property name.
You do not need getters, setters, or extra annotations.
Reading: from JSON to record
A record has no setters, and its fields are final. Jackson therefore builds the object by calling the canonical constructor, the one whose parameters match the record components. It reads the parameter names from the record's metadata, so you don't need the -parameters compiler flag.
The following program writes a record to JSON and reads one back:
import com.fasterxml.jackson.databind.ObjectMapper;
public class RecordJsonDemo {
public record UserResponse(Long id, String name, String email) {
}
public static void main(String[] args) throws Exception {
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(
new UserResponse(1L, "Ada", "[email protected]"));
System.out.println(json);
UserResponse parsed = mapper.readValue(
"{\"id\":2,\"name\":\"Linus\"}", UserResponse.class);
System.out.println(parsed);
}
}The output is:
{"id":1,"name":"Ada","email":"[email protected]"}
UserResponse[id=2, name=Linus, email=null]The second JSON document has no email property. Jackson still builds the record and passes null for the missing component.
The round trip
The diagram shows where Jackson enters and leaves the record.
In a Spring MVC controller, Spring's message converter does this work. @RequestBody triggers the read path and a returned record triggers the write path.
What happens with imperfect input
Because Jackson goes through the constructor, input that doesn't match the record has predictable results.
| JSON input | Result |
|---|---|
| A property is missing | The component is `null`, or `0` or `false` for primitives |
| A property is `null` | The component is `null`, or `0` or `false` for primitives |
| An unknown property is present | Ignored in Spring Boot, which turns off `FAIL_ON_UNKNOWN_PROPERTIES`. A plain `new ObjectMapper()` throws. |
| A value has the wrong type, such as `"age": "abc"` for an `int` | Deserialization fails, and Spring answers with 400 Bad Request |
The primitive default is a common source of bugs. With int age, a client that forgets the age property sends the same data as one that sends "age": 0. A @Min(18) check would reject both. Without validation, use a wrapper type such as Integer if you must tell "absent" from "zero".
Constructors run on the way in
Jackson calls the canonical constructor, so any compact constructor logic runs during deserialization. If the constructor throws an exception, Jackson wraps it, and Spring MVC normally returns 400 Bad Request. Normalization such as stripping whitespace therefore applies to every request body that arrives as a record. Later chapters cover compact constructors in detail.
Other record types
Several other shapes work without extra setup:
- Nested records and collections, such as
List<String>components. - Generic records, for example
record Page<T>(List<T> items, int total). Spring can deserialize them if the controller declares the full type. - Dates, if the Java time module is registered. Spring Boot registers it for you.
One limitation is that a record cannot inherit from a class, so a JSON type hierarchy is awkward. Records can implement interfaces, which is the usual route for polymorphic payloads. If you need different JSON property names or want to hide a component, Jackson annotations on the record components handle that. A later chapter covers them.
Checking the behavior yourself
When a request fails and the cause is unclear, test Jackson alone with a plain ObjectMapper, as in the demo above. This separates JSON binding problems from validation and controller problems. Remember that Spring Boot's mapper is configured differently. For an identical setup, inject the ObjectMapper bean or use @JsonTest, which a later chapter covers.
Exercise
A client sends {"name": "Ada"} to an endpoint that takes record CreateUserRequest(String name, int age). Spring Boot's default Jackson setup is in use. What does the controller receive, and how could you make the missing age detectable?
Show answer
The controller receives a record with name "Ada" and age 0, because Jackson passes the default value for a missing primitive. To detect the missing value, change the component to Integer age and add @NotNull (with @Valid on the parameter). A missing age then stays null and fails validation.