Sub topic 10
Renaming and shaping JSON with Jackson annotations
By default Jackson uses your record component names as JSON property names. That works until a client expects full_name, a date has to look like 31/12/1990, or you want to leave null fields out of a response. This chapter covers the Jackson annotations that handle these cases on record DTOs, and the settings that apply the same rules to the whole application.
Prerequisites
This chapter assumes you have read the earlier chapters on how Jackson binds records and on request and response DTOs. You should be comfortable with:
- Declaring a record and using it as a
@RequestBodyor a response type. - Spring Boot 3.1 or later, which ships Jackson 2.15 or later.
- Basic JSON syntax.
The version matters. Jackson 2.15 reworked its handling of records, and annotations on record components behave much more consistently from that version on. The examples use annotations from com.fasterxml.jackson.annotation, which spring-boot-starter-web brings in through spring-boot-starter-json.
Where annotations go on a record
A record component such as String name is declared once, but Java generates several members from it: a private field, an accessor method name(), and a constructor parameter. When you annotate a component, Java copies the annotation to each of those places that the annotation type allows.
Jackson's annotations such as @JsonProperty allow fields, methods and parameters. The annotation therefore reaches the field, the accessor and the constructor parameter. Serialization (record to JSON) and deserialization (JSON to record) both see it. You write it once, in the record header, and both directions stay in sync.
Renaming properties with @JsonProperty
@JsonProperty sets the JSON name for a component.
import com.fasterxml.jackson.annotation.JsonProperty;
public record UserResponse(
Long id,
@JsonProperty("full_name") String name,
@JsonProperty("email_address") String email) {
public static UserResponse from(User user) {
return new UserResponse(user.getId(), user.getName(), user.getEmail());
}
}A controller that returns this record produces:
{"id":1,"full_name":"Ada","email_address":"[email protected]"}Only the JSON changes. In Java you still call response.name(). This is the main benefit of a DTO. The wire format and the Java model can differ without touching the entity or the service layer.
The same annotation on a request record controls which JSON key Jackson reads. If the client sends name instead of full_name, the component stays null (or 0 for a primitive). Spring Boot does not reject the unknown key by default, so you get a missing value with no error. Bean Validation can catch this if the component has @NotBlank.
Accepting several names with @JsonAlias
When you rename a property in a published API, old clients keep sending the old name. @JsonAlias lets deserialization accept extra names. It has no effect on serialization, which always uses the primary name.
import com.fasterxml.jackson.annotation.JsonAlias;
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.constraints.NotBlank;
public record CreateUserRequest(
@NotBlank
@JsonProperty("full_name")
@JsonAlias({"name", "fullName"})
String name) {
}All three bodies below bind to the same record value:
{"full_name": "Ada"}
{"name": "Ada"}
{"fullName": "Ada"}Use aliases for a migration period, then remove them. If you keep accumulating them, the API contract becomes hard to describe.
Naming strategies
Annotating every component gets tedious when the whole payload uses snake_case. Jackson has naming strategies that convert Java names mechanically. You can apply one to a single record with @JsonNaming:
import com.fasterxml.jackson.databind.PropertyNamingStrategies;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import java.time.LocalDate;
@JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class)
public record AccountResponse(Long accountId, String ownerName, LocalDate openedOn) {
}This produces account_id, owner_name and opened_on.
To apply the strategy to every DTO in the application, set it in application.properties:
spring.jackson.property-naming-strategy=SNAKE_CASEAn explicit @JsonProperty always wins over a naming strategy, so you can use a global strategy and still override one awkward field.
Leaving fields out of the output
By default a null component is written as "nickname": null. Some clients prefer that the key be absent. @JsonInclude controls this.
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({"id", "name", "email", "nickname"})
public record ProfileResponse(Long id, String name, String email, String nickname) {
@JsonProperty("display_name")
public String displayName() {
return nickname != null ? nickname : name;
}
}Three things happen here:
@JsonInclude(NON_NULL)on the record omits any null component. Whennicknameisnull, the key is missing.@JsonPropertyOrderfixes the order of keys. Without it, Jackson follows the declaration order of the components, which is usually fine. Set an order explicitly when you want stable output for snapshot tests or for human readers.displayName()is an extra method, not a component. Annotating it with@JsonPropertyadds a computeddisplay_nameproperty to the output. Records can have extra instance methods, so a derived value does not need a stored field.
For new ProfileResponse(1L, "Ada", "[email protected]", null) the output is:
{"id":1,"name":"Ada","email":"[email protected]","display_name":"Ada"}Other Include values are NON_EMPTY (also drops empty strings, collections and maps) and NON_ABSENT (drops null and empty Optional). To apply a rule everywhere, use a property:
spring.jackson.default-property-inclusion=non_nullThe computed property exists only in the output. If a client sends display_name back in a request body, Jackson has no matching constructor parameter. Treat such records as response-only, and do not reuse them as request bodies.
Formatting dates and numbers
@JsonFormat sets how a value is written and read. It is mostly used for dates.
import com.fasterxml.jackson.annotation.JsonFormat;
import java.time.LocalDate;
public record CreateEventRequest(
String title,
@JsonFormat(pattern = "dd/MM/yyyy") LocalDate date) {
}This record accepts {"title":"Launch","date":"31/12/2026"}. Without the annotation, Jackson expects ISO-8601 (2026-12-31).
Spring Boot already turns off WRITE_DATES_AS_TIMESTAMPS, so LocalDate and Instant values are written as ISO strings, not as arrays or epoch numbers. Do not add @JsonFormat out of habit. Only use it when you must deviate from ISO-8601. Custom date formats are easy to get wrong across time zones and locales, and ISO-8601 is the format most clients already parse.
Ignoring and tolerating properties
Two annotations deal with properties you do not want to handle.
| Annotation | Where it goes | Effect |
|---|---|---|
| `@JsonIgnore` | A component or method | Excludes the property from JSON |
| `@JsonIgnoreProperties({"a", "b"})` | The record | Ignores the named properties |
| `@JsonIgnoreProperties(ignoreUnknown = true)` | The record | Ignores any key the record does not declare |
| `@JsonProperty(access = READ_ONLY)` | A component | Written in output, ignored in input |
Before reaching for @JsonIgnore on a record component, ask whether the component belongs in the record at all. A response record that must hide a field simply should not declare it. This is the reason to map entities to DTOs in the first place. The handling of @JsonIgnore on record components has changed between Jackson versions, and a hidden component still has to be supplied to the constructor during deserialization. If you do use it, test both directions.
Unknown keys deserve a specific note. Plain Jackson fails on unknown keys, but Spring Boot's auto-configured ObjectMapper turns that failure off. A request with a typo such as emial therefore binds without an error, and email is null. If you prefer a strict API, turn the check back on:
spring.jackson.deserialization.fail-on-unknown-properties=trueClients then get a 400 Bad Request for unknown keys. This catches typos early, but it also breaks clients when you add a field they echo back, so decide per API.
Choosing a constructor with @JsonCreator
Records have one canonical constructor, and Jackson uses it automatically. You rarely need @JsonCreator on a record. It becomes useful when you want to accept a different JSON shape, for example a single string value:
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;
public record Email(String value) {
@JsonCreator
public Email {
if (value == null || !value.contains("@")) {
throw new IllegalArgumentException("Invalid email");
}
}
@JsonValue
public String value() {
return value;
}
}@JsonValue makes the whole record serialize as the plain string "[email protected]", and @JsonCreator makes a plain JSON string deserialize back into it. Use this pattern for small value types. If a record with @JsonValue appears as a component of another record, the nested JSON stays flat: {"email":"[email protected]"}, not {"email":{"value":"..."}}.
Annotations at a glance
| Goal | Annotation | Works on input | Works on output |
|---|---|---|---|
| Rename a property | `@JsonProperty` | Yes | Yes |
| Accept old names | `@JsonAlias` | Yes | No |
| Rename everything | `@JsonNaming` or `spring.jackson.property-naming-strategy` | Yes | Yes |
| Drop null fields | `@JsonInclude` | No | Yes |
| Set key order | `@JsonPropertyOrder` | No | Yes |
| Format dates | `@JsonFormat` | Yes | Yes |
| Add a computed field | `@JsonProperty` on a method | No | Yes |
Validation errors use Java names
Renaming has one side effect that surprises people. Bean Validation knows nothing about Jackson. When @Valid fails, Spring's MethodArgumentNotValidException reports each failing field by its Java name. For the CreateUserRequest above, the error refers to the field name, even though the client sent full_name.
If you build error responses from FieldError.getField(), clients see a name they never used. Either document the mapping, or translate the names in your exception handler. The simplest approach is to keep the Java component names and the JSON names close enough that this rarely matters.
Testing the JSON shape
The @JsonTest slice from the testing chapter is the right tool for checking these annotations. It loads only the Jackson configuration, including any spring.jackson.* properties, so it verifies the real mapper settings.
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.json.JsonTest;
import org.springframework.boot.test.json.JacksonTester;
@JsonTest
class UserResponseNamingTest {
@Autowired
private JacksonTester<UserResponse> json;
@Test
void writesRenamedFields() throws Exception {
UserResponse response = new UserResponse(1L, "Ada", "[email protected]");
assertThat(json.write(response)).extractingJsonPathStringValue("$.full_name").isEqualTo("Ada");
assertThat(json.write(response)).doesNotHaveJsonPath("$.name");
}
@Test
void readsRenamedFields() throws Exception {
String content = """
{"id": 1, "full_name": "Ada", "email_address": "[email protected]"}
""";
UserResponse parsed = json.parseObject(content);
assertThat(parsed.name()).isEqualTo("Ada");
assertThat(parsed.email()).isEqualTo("[email protected]");
}
}The second test matters as much as the first. A rename that works on output but not on input is a common mistake with older Jackson versions, and a round-trip test catches it.
Common errors
- A property is
nullafter deserialization. The client's key does not match the JSON name. Check@JsonProperty, any naming strategy, and capitalization. The lenient unknown-key default hides the mismatch. - A
@JsonFormatpattern is ignored. The pattern applies to the type it is written for. AStringcomponent ignores a date pattern, so the component must be aLocalDateor similar. - Null fields still appear.
@JsonIncludeon a component affects only that component. Put it on the record to cover all components. - A global naming strategy renames a field you did not expect. Check for an explicit
@JsonPropertyon that component, because it overrides the strategy. - Errors mention a different field name than the client sent. Validation uses Java names, as described above.
Exercise
A ProductResponse record has components Long id, String name and String description. The API must send product_name instead of name, omit description when it is null, and accept title as an alternative input name for name. Which annotations do you put where?
Show answer
Put @JsonInclude(JsonInclude.Include.NON_NULL) on the record so a null description is omitted. Put @JsonProperty("product_name") and @JsonAlias("title") on the name component. @JsonProperty sets the name used for both input and output, and @JsonAlias adds title as an extra accepted input name without changing the output. Check the result with a @JsonTest that writes the record and reads a body that uses title.
Exercise
Your record carries @JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class), and one component String sku has @JsonProperty("SKU"). What JSON key does sku get?
Show answer
SKU. An explicit @JsonProperty name takes precedence over a naming strategy, so the strategy applies only to components without one.