Sub topic 2
DTOs and JSON with Jackson
Assume you know Java records, basic HTTP, and dependency injection. This chapter uses Spring Boot with the spring-boot-starter-web dependency.
DTOs and JSON with Jackson
A data transfer object (DTO) is a Java type used to carry data across an application boundary. A REST API commonly uses separate DTOs for incoming requests and outgoing responses. This prevents database entities and internal fields from becoming part of the public API.
Jackson is Spring Boot’s JSON library. It converts JSON into Java objects and Java objects into JSON.
public record CreateBookRequest(
String title,
String author) {
}
public record BookResponse(
long id,
String title,
String author) {
}For example, this JSON becomes a CreateBookRequest:
{
"title": "Dune",
"author": "Frank Herbert"
}Jackson matches JSON property names to record components. The response record is serialized back into JSON when a controller returns it.
Accepting JSON with `@RequestBody`
Use @RequestBody on a method parameter when the request body contains JSON. Spring asks Jackson to deserialize the body into the declared DTO type.
@PostMapping
public BookResponse create(@RequestBody CreateBookRequest request) {
return service.create(request);
}The controller receives a typed object instead of manually reading strings from the request. If the JSON is malformed or cannot be converted, Spring returns a client error. Add @Valid and Bean Validation annotations when the input must satisfy rules:
public record CreateBookRequest(
@NotBlank @Size(max = 200) String title,
@NotBlank String author) {
}
@PostMapping
public BookResponse create(@Valid @RequestBody CreateBookRequest request) {
return service.create(request);
}Validation requires the Bean Validation dependency, usually included by spring-boot-starter-validation.
Controlling responses with `ResponseEntity`
ResponseEntity<T> lets a controller choose the body, status code, and headers. A successful creation normally returns 201 Created and a Location header pointing to the new resource.
@PostMapping
public ResponseEntity<BookResponse> create(
@Valid @RequestBody CreateBookRequest request) {
BookResponse created = service.create(request);
URI location = ServletUriComponentsBuilder
.fromCurrentRequest()
.path("/{id}")
.buildAndExpand(created.id())
.toUri();
return ResponseEntity.created(location).body(created);
}Exercise
Which annotation tells Spring to deserialize a JSON request body into a Java parameter?
Show answer
@RequestBody.