Sub topic 3
How Jackson reads and writes records
This chapter assumes you can write a basic Spring Boot @RestController, you know what a Java record is, and you have Java 17 or later. Jackson is the library Spring Boot uses to convert between Java objects and JSON. You will see how it handles records in both directions, which defaults can surprise you, and how to configure it when they do.
What Spring Boot gives you
Spring Boot's spring-boot-starter-web brings in Jackson and configures one shared ObjectMapper. Spring MVC uses that mapper to do two jobs:
- Deserialization: turn the JSON request body into the object type of your
@RequestBodyparameter. - Serialization: turn the object you return from a controller method into the JSON response body.
Jackson has supported records since version 2.12. Any current Spring Boot release uses a version that works with them, so you do not need extra modules or annotations for the basic case. Records are a good fit for JSON for a simple reason. A record is a fixed list of named components, and a JSON object is a set of named values.
Writing a record to JSON
A record has no getters named getName(). It has accessor methods named after the components: name(), email(), age(). Jackson recognizes records and uses the record components as the JSON properties. The property names come from the component names.
import com.fasterxml.jackson.databind.ObjectMapper;
public class RecordJsonDemo {
public record CreateUserRequest(String name, String email, int age) {
}
public static void main(String[] args) throws Exception {
ObjectMapper mapper = new ObjectMapper();
CreateUserRequest request = new CreateUserRequest("Ada", "[email protected]", 36);
System.out.println(mapper.writeValueAsString(request));
}
}This prints:
{"name":"Ada","email":"[email protected]","age":36}The properties normally appear in the order the components are declared. Do not rely on that order in clients. JSON objects are unordered by definition.
Reading JSON into a record
Deserialization uses the record's canonical constructor. This is the constructor whose parameters match the components exactly. Jackson finds the parameter names by reading the record components through reflection. You do not need @JsonCreator, @JsonProperty, or the -parameters compiler flag. A plain class needs one of those for constructor binding. A record does not.
import com.fasterxml.jackson.databind.ObjectMapper;
public class RecordReadDemo {
public record CreateUserRequest(String name, String email, int age) {
}
public static void main(String[] args) throws Exception {
ObjectMapper mapper = new ObjectMapper();
CreateUserRequest full = mapper.readValue(
"{\"name\":\"Ada\",\"email\":\"[email protected]\",\"age\":36}",
CreateUserRequest.class);
System.out.println(full);
CreateUserRequest partial = mapper.readValue(
"{\"name\":\"Ada\"}",
CreateUserRequest.class);
System.out.println(partial);
}
}The output is:
CreateUserRequest[name=Ada, email=null, age=0]preceded by the line for the full request:
CreateUserRequest[name=Ada, [email protected], age=36]The second result is the important one. The JSON had no email and no age, and Jackson did not complain. It passed null for the missing String and 0 for the missing int to the constructor. Records are immutable, so Jackson cannot create an empty object and fill it in later with setters. It must collect all the values first and then call the constructor once.
The request path from end to end
The diagram shows what happens when a client posts JSON to a controller that takes a record.
Two details follow from this order. The constructor runs before validation. If your compact constructor throws, validation never happens. Bean Validation also sees the record after any normalization the constructor did.
Defaults that surprise people
The table summarizes how Jackson, with Spring Boot's defaults, treats common input problems.
| Situation | Result | Why |
|---|---|---|
| Property missing, component is a reference type | `null` is passed | Jackson passes the default for the type |
| Property missing, component is a primitive such as `int` | `0` (or `false`) is passed | `FAIL_ON_NULL_FOR_PRIMITIVES` is off by default |
| Property present with value `null`, primitive component | `0` is passed | Same setting |
| Extra property in the JSON | Ignored | Spring Boot turns off `FAIL_ON_UNKNOWN_PROPERTIES` |
| Wrong type, such as `"age":"abc"` | 400 response | Jackson throws, Spring maps it to `HttpMessageNotReadableException` |
| Malformed JSON | 400 response | Same exception |
| Compact constructor throws | 400 response | Jackson wraps the exception, Spring treats the body as unreadable |
Note that a plain new ObjectMapper() differs from Spring Boot's mapper on one row. A plain mapper fails on unknown properties, while Spring Boot's mapper ignores them. If you test with new ObjectMapper() and your application behaves differently, this is a likely cause.
Missing primitives become zero
The primitive default is the one that causes real bugs. A client that forgets age gets age = 0, which looks like valid data to your code. You have two ways to handle it.
The first is to use a wrapper type and require it. A wrapper such as Integer can be null, so validation can tell "absent" from "zero".
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotNull;
public record CreateUserRequest(
String name,
String email,
@NotNull @Min(18) Integer age) {
}The second is to make Jackson itself reject the input. Add this to application.properties:
spring.jackson.deserialization.fail-on-null-for-primitives=trueWith this setting, an explicit "age": null fails with a 400. Be aware that it only covers explicit nulls. A property that is completely absent is still passed as 0 unless you also use FAIL_ON_MISSING_CREATOR_PROPERTIES. The wrapper type plus @NotNull is the simpler and more predictable choice.
Rejecting unknown properties
If you want a strict API that rejects typos in property names, turn the check back on:
spring.jackson.deserialization.fail-on-unknown-properties=trueStrictness has a cost. Clients that send extra fields start failing, which makes it harder to evolve your API without breaking them. Many teams leave the Spring Boot default and accept the leniency.
Nested records, collections, and dates
Records compose. A record can hold other records and collections, and Jackson builds them recursively, using each nested record's canonical constructor.
import java.time.LocalDate;
import java.util.List;
public record OrderRequest(
String customerId,
Address shipTo,
List<OrderLine> lines,
LocalDate requestedDelivery) {
public record Address(String street, String city) {
}
public record OrderLine(String sku, int quantity) {
}
}This accepts a body like the following:
{
"customerId": "c-42",
"shipTo": { "street": "1 Main St", "city": "Leeds" },
"lines": [ { "sku": "A-1", "quantity": 2 } ],
"requestedDelivery": "2026-12-24"
}Spring Boot registers Jackson's java.time support. Dates use ISO-8601 text such as 2026-12-24, and WRITE_DATES_AS_TIMESTAMPS is off, so responses use the same text form instead of numeric arrays. If you build your own ObjectMapper with new ObjectMapper(), the java.time module is not registered. Call findAndRegisterModules() on the mapper, or Jackson will refuse to handle LocalDate.
A missing lines property arrives as null, not as an empty list. Code that loops over lines() will then throw NullPointerException. You can guard against that in a compact constructor, which a later chapter covers.
When a constructor rejects the input
Jackson calls your compact constructor for every record it creates. If the constructor throws, Jackson reports a failure to create the value and Spring answers with 400. The message names the cause.
public record Percentage(int value) {
public Percentage {
if (value < 0 || value > 100) {
throw new IllegalArgumentException("value must be between 0 and 100");
}
}
}This is useful for invariants that no client input should ever violate. It is a weaker fit for ordinary form-style validation. A constructor failure gives one error and stops. Bean Validation can collect every violated field and report them together. Use the constructor for "this object must never exist in this state" and annotations for "tell the client everything that is wrong".
Controlling the shape of the JSON
You can change names and visibility with the same annotations you would use on a class. They go on the record components.
import com.fasterxml.jackson.annotation.JsonProperty;
public record UserResponse(
Long id,
@JsonProperty("full_name") String name,
String email) {
}With this declaration the JSON uses full_name for both reading and writing. The Java accessor is still name(). A later chapter covers these annotations in detail. For now, note that annotations on a record component are propagated to the places Jackson looks, so you place them once on the component and do not need to repeat them on fields or accessors.
A record can also have extra methods. Jackson does not treat an ordinary method as a property, because record serialization is based on components. If you want a computed value in the JSON, mark the method explicitly:
import com.fasterxml.jackson.annotation.JsonProperty;
public record Rectangle(double width, double height) {
@JsonProperty
public double area() {
return width * height;
}
}On the way in, though, area has no matching constructor parameter. If a client sends it, it counts as an unknown property. Spring Boot ignores it by default, but a strict mapper would reject it. Use @JsonProperty(access = JsonProperty.Access.READ_ONLY) if you want to state that intent clearly.
Common mistakes
- Using a plain
ObjectMapperin tests and expecting Spring Boot behavior. Inject the application's mapper, or use@JsonTest, which configures it for you. - Using
int,long, orbooleanfor required fields. A missing value silently becomes0orfalse. Use wrapper types for anything the client must supply. - Expecting setters to run. Records have none, and Jackson never calls a mutator on a record. Everything flows through the constructor.
- Returning an entity and hoping a record will fix it later. The record only protects you if the controller actually returns it. Map the entity into a record, as the later chapters show.
Exercises
Exercise
A client posts {"name":"Ada","email":"[email protected]"} to an endpoint that takes record CreateUserRequest(String name, String email, int age). No validation annotations are present and you use Spring Boot's default ObjectMapper. What does the controller receive for age, and what single change to the record lets Bean Validation detect that the field was missing?
Show answer
The controller receives age = 0, because Jackson passes the default value for a missing primitive and does not fail. Changing the component to the wrapper type Integer age and adding @NotNull makes the missing value arrive as null, so validation can reject it.
Exercise
Why does Jackson not need @JsonCreator or the -parameters compiler flag to deserialize a record, and why can it not use setters instead of a constructor?
Show answer
Jackson reads the record components by reflection, which gives it the names and order of the canonical constructor's parameters, so it can bind JSON properties to them directly. Records are immutable and have no setters, so the only way to create one is to collect all values first and call the canonical constructor once.
Exercise
Your compact constructor throws IllegalArgumentException when a value is out of range. What HTTP status does a client see when it posts such a body, and why does Bean Validation not report anything for that request?
Show answer
The client sees 400. Jackson wraps the exception while creating the record, and Spring treats the body as unreadable. Validation runs only after the record exists, so it never runs when the constructor throws.