Sub topic 6
DTOs and JSON with Jackson
This chapter covers how a Spring Boot controller turns Java objects into JSON and back, and why those objects should be dedicated DTOs rather than your domain or database classes. It assumes you can write Java records, know what @RestController does, and have a Spring Boot web project with spring-boot-starter-web. That starter brings in Jackson, the JSON library Spring MVC uses by default.
What a DTO is and why you need one
A DTO (data transfer object) is a class whose only job is to carry data across a boundary. In a REST API the boundary is the HTTP message. Your controller receives a request DTO, hands it to the service layer, and returns a response DTO.
You could skip DTOs and return your domain objects (for example a JPA entity) directly. This works in a demo and causes problems later:
- Accidental exposure. Any getter on the entity becomes part of the public API. A new
internalNotesorpasswordHashfield leaks the moment someone adds it. - Coupling. Renaming a database column or restructuring an entity changes the JSON contract and breaks clients.
- Mass assignment. If you accept an entity as the request body, a client can set fields it should not control, such as
idorrole. - Different shapes. Creating a book needs
titleandauthor. Reading one also returnsid. One class cannot describe both without nullable fields and special cases.
Separate DTOs fix all four. The cost is a small mapping step between DTO and domain object.
Records as DTOs
Java records suit DTOs. They are immutable, have no boilerplate, and Jackson (2.12 and later, which Spring Boot 3 ships) reads and writes them without extra configuration. The two DTOs from this tutorial's book API are:
public record CreateBookRequest(
@NotBlank @Size(max = 200) String title,
@NotBlank String author) {}
public record BookResponse(long id, String title, String author) {}Jackson uses the record's canonical constructor to deserialize and its accessor methods (title(), not getTitle()) to serialize. The JSON property names match the component names: {"id":1,"title":"Dune","author":"Frank Herbert"}. The constraint annotations on CreateBookRequest are used in the validation chapter. Here they only show that DTOs are a natural place to declare input rules.
How the conversion happens
You never call Jackson yourself in a controller. Spring MVC uses an HttpMessageConverter for this. For JSON, the converter is MappingJackson2HttpMessageConverter, and it wraps a Jackson ObjectMapper that Spring Boot builds and configures for you.
On a request, the converter reads the body when it sees a @RequestBody parameter and the Content-Type is application/json. On a response, it writes the returned object (or the body of a ResponseEntity) when @RestController is in effect. Malformed JSON, or JSON of the wrong type for a field, makes Jackson throw, and Spring MVC turns that into a 400 Bad Request.
The mapping step
Put the conversion between domain objects and DTOs in one predictable place. A static factory on the response record is enough for most projects:
public record BookResponse(long id, String title, String author) {
public static BookResponse from(Book book) {
return new BookResponse(book.getId(), book.getTitle(), book.getAuthor());
}
}The service calls BookResponse.from(book) before returning, or the controller does if your service returns domain objects. Pick one layer and stay consistent. Libraries such as MapStruct generate this code once your DTOs have dozens of fields, but hand-written mapping is clearer for small ones and fails at compile time when a field is renamed.
Controlling the JSON shape
Jackson's defaults are reasonable. When you need something different, annotations on the DTO change the output. The following program runs without Spring so you can try the behavior directly:
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.json.JsonMapper;
import java.time.LocalDate;
public class JacksonDemo {
@JsonInclude(JsonInclude.Include.NON_NULL)
public record BookResponse(
long id,
String title,
String author,
@JsonProperty("published_on") LocalDate publishedOn,
String subtitle) {}
public static void main(String[] args) throws Exception {
var mapper = JsonMapper.builder()
.findAndAddModules()
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
.build();
var book = new BookResponse(1, "Dune", "Frank Herbert", LocalDate.of(1965, 8, 1), null);
String json = mapper.writeValueAsString(book);
System.out.println(json);
BookResponse back = mapper.readValue(json, BookResponse.class);
System.out.println(back);
}
}The first line printed is {"id":1,"title":"Dune","author":"Frank Herbert","published_on":"1965-08-01"}. The null subtitle is omitted, and publishedOn is written as published_on. The second line is the record read back from that JSON. You need jackson-databind and jackson-datatype-jsr310 on the classpath, which spring-boot-starter-web already provides.
The annotations you will use most often are:
| Annotation | Effect |
|---|---|
| `@JsonProperty("name")` | Uses a different JSON name for a field or record component |
| `@JsonIgnore` | Leaves a property out of both serialization and deserialization |
| `@JsonInclude(NON_NULL)` | Omits null properties from the output |
| `@JsonFormat(pattern = "...")` | Sets the text format of dates and numbers |
| `@JsonIgnoreProperties(ignoreUnknown = true)` | Tolerates unknown JSON fields on one class |
| `@JsonAlias({"a", "b"})` | Accepts extra names for a property when reading |
Prefer DTOs with only the fields you want to expose over @JsonIgnore on a shared class. An allow-list is safer than a block-list.
What Spring Boot configures for you
Spring Boot builds its ObjectMapper through Jackson2ObjectMapperBuilder and changes several Jackson defaults. Three matter in practice:
FAIL_ON_UNKNOWN_PROPERTIESis disabled. A request with extra fields is accepted and the extras are ignored. Plain Jackson would reject it.WRITE_DATES_AS_TIMESTAMPSis disabled. ALocalDateis written as"1965-08-01"instead of[1965,8,1].- Modules found on the classpath are registered automatically, including the
java.timemodule and the parameter names module.
You adjust the mapper through spring.jackson.* properties instead of creating your own bean:
spring.jackson.property-naming-strategy=SNAKE_CASE
spring.jackson.default-property-inclusion=non_null
spring.jackson.deserialization.fail-on-unknown-properties=trueThe first line writes every property in snakecase (`publishedon) without per-field annotations. The second omits nulls everywhere. The third makes the API strict, so a client that misspells titel gets a 400` response instead of a silently missing title.
Common errors
- Missing property, no error. Because unknown properties are ignored, a typo in a client's JSON gives a DTO field that is
nullor0. Validation (@NotBlank) catches the null case. Enablingfail-on-unknown-propertiescatches the typo itself. - Primitives default silently. If a request DTO has
int quantityand the client omits it, the value becomes0. UseIntegerwhen absence is meaningful, and add@NotNull. - Dates as arrays. Output like
[1965,8,1]meansWRITE_DATES_AS_TIMESTAMPSis on, usually because you built your own mapper. - Infinite recursion. Returning entities with bidirectional relationships (a
Bookwith anAuthorthat lists itsBooks) makes Jackson loop untilStackOverflowError. Response DTOs avoid this, because you choose exactly which fields to copy. - Lazy-loading surprises. Serializing a JPA entity can trigger database queries or a
LazyInitializationExceptionoutside a transaction. DTOs built inside the service layer avoid it. - Wrong content type. A body sent without
Content-Type: application/jsonproduces415 Unsupported Media Type, even if the JSON is valid.
Where to put DTOs
Keep the DTOs next to the controller that uses them, for example in a book package with BookController, BookService, CreateBookRequest and BookResponse. Or put them in a dto sub-package if the project is small. Nested records inside the controller class hide them from other code but make the controller file long. Whichever you choose, apply it to every resource in the project.
Exercise
A client sends POST /api/books with the body {"titel": "Dune", "author": "Frank Herbert"} (note the typo). With Spring Boot's default Jackson settings and CreateBookRequest as defined in this chapter, what happens, and which two changes would make the API report the problem clearly?
Show answer
Spring Boot disables FAILONUNKNOWN_PROPERTIES, so Jackson ignores "titel" and creates the record with title = null. The request is still deserialized. If the controller uses @Valid, @NotBlank on title then rejects it with a 400, though the message says title is blank and does not mention the typo. If @Valid is missing, the null title reaches the service. Two changes: add @Valid to the @RequestBody parameter so the null title is rejected, and set spring.jackson.deserialization.fail-on-unknown-properties=true so Jackson returns 400 and names the unknown property "titel".
Exercise
Why is returning a JPA entity directly from a controller risky, even if it works today? Name two concrete problems.
Show answer
Every getter becomes part of the public JSON contract, so adding a sensitive field to the entity (such as a password hash) exposes it automatically, and renaming a column changes the API and breaks clients. Other valid answers: bidirectional relationships cause infinite recursion during serialization, lazy-loaded associations can trigger queries or a LazyInitializationException, and accepting an entity as the request body lets clients set fields like id or role (mass assignment).