Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 66 ยท Building REST APIs

Request and Response Bodies with Jackson

How Spring Boot turns JSON into Java objects and back: @RequestBody, records as DTOs, message converters, Jackson settings, dates and DTO vs entity.

A REST API is mostly a conversation in JSON. A client sends a body, your controller works with a Java object, and the answer goes back as another body. Spring Boot does the translation in both directions, and almost everything you need to know about it fits in one idea: a controller method declares types, and a converter turns bytes into those types and back.

This lesson shows how that translation works, how to shape the objects that cross the wire (records are the best fit), how Boot configures Jackson for you, and why you should almost never send a database entity straight to a client. If you have not seen controllers yet, read REST Controllers first. For Jackson itself, outside Spring, see JSON with Jackson and Advanced Jackson.

The real Spring Boot cannot run on this site, so the controller code below is read-only. The runnable examples use real Jackson (the same library Boot uses) on our Java runner. One detail: Boot 4 uses Jackson 3 (package tools.jackson), while our runner provides Jackson 2 (com.fasterxml.jackson). The annotations and the ideas are the same.

From bytes to objects and back

Two annotations mark the body:

  • @RequestBody on a parameter says "build this argument from the request body".
  • @RestController (or @ResponseBody) says "turn the return value into the response body".
Java
record CreateBookRequest(String title, String author, int pages) {}
record BookResponse(long id, String title, String author) {}

@RestController
@RequestMapping("/books")
class BookController {

    @PostMapping
    ResponseEntity<BookResponse> create(@RequestBody CreateBookRequest request) {
        BookResponse saved = bookService.create(request);
        return ResponseEntity
            .created(URI.create("/books/" + saved.id()))
            .body(saved);
    }
}

The work in the middle is done by an HttpMessageConverter. Spring keeps an ordered list of them. For a request, it looks at the Content-Type header and the target type, and picks the first converter that can read that combination. For a response, it looks at the Accept header and the return type and picks one that can write it. With Jackson on the classpath (the web starter brings it), JSON is handled by a Jackson converter; plain strings and byte arrays have their own converters.

What happens to a request body

Header check Content-Type picks a converter.
Deserialize Jackson builds your record.
Validate Optional @Valid runs next.
Call the method The controller gets a typed object.
1 / 2

If the JSON is malformed, or a number field holds text, the conversion fails before your method is called and Boot answers 400 Bad Request. A body with a Content-Type nobody can read gives 415. You will shape those error responses in Error Handling and Problem Details.

Records as DTOs

A DTO (data transfer object) is a class whose only job is to describe what crosses the API boundary. Java records suit it perfectly: they are immutable, have no boilerplate, and Jackson reads and writes them without extra annotations.

Java Records and real Jackson

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The first line shows the record built from JSON; the second shows the record written back. Notice the date: Jackson needs the JavaTimeModule to understand LocalDate, and without further settings it would write a date as an array of numbers. That surprise is the subject of a later section.

What Boot configures for you

In a plain Java program you build the mapper yourself, as above. In Boot you never do: the auto-configuration creates one shared JsonMapper bean with sensible settings and hands it to the message converter. The most important defaults:

  • Java time types are supported, and dates are written as ISO-8601 strings, not as timestamps.
  • Unknown properties are ignored when reading, so a client that sends an extra field does not get an error.
  • Properties with null values are written (switch this off with spring.jackson.default-property-inclusion=non_null).
  • Modules found on the classpath are registered automatically.

You tune the mapper with properties or by adding your own customizer bean, never by calling new ObjectMapper() in a controller. A separate mapper would ignore every setting Boot made, and your API would behave differently from the rest of the application.

YAML
spring:
  jackson:
    default-property-inclusion: non_null
    serialization:
      indent-output: false
    deserialization:
      fail-on-unknown-properties: false

The property names stay under the spring.jackson prefix across Boot versions, but check the reference for your exact release, since the Jackson 2 to Jackson 3 move renamed some feature enums.

The next TryIt compares a strict mapper (Jackson's own defaults) with a Boot-style mapper on the same input. It is the quickest way to see why an extra field fails in one program and passes in another.

Java Jackson defaults versus Boot-style defaults

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Both settings are deliberate API choices. Ignoring unknown fields lets old servers accept requests from newer clients. Strictness has its uses too (a typo such as quantitty is silently dropped when unknown fields are ignored), so some teams switch fail-on-unknown-properties back on for write endpoints.

Shaping the JSON

Small annotations from com.fasterxml.jackson.annotation (the package Jackson 3 kept for annotations) adjust the output without changing the Java names:

  • @JsonProperty("full_name") renames a field.
  • @JsonIgnore hides a field in both directions; @JsonProperty(access = READ_ONLY) hides it only when reading.
  • @JsonInclude(NON_NULL) omits nulls for one type.
  • @JsonFormat(pattern = "dd/MM/yyyy") sets a date format for one field.

Use them sparingly. If you need many, the DTO is probably not shaped like the API you want, and a second DTO is cleaner than a pile of annotations.

Dates and times

Send dates as ISO-8601 strings: 2031-03-09 for a LocalDate, 2031-03-09T14:30:00Z for an Instant. They are unambiguous, sort correctly as text and every language parses them. Avoid epoch numbers and locale formats such as 03/09/2031, which means two different days in two countries. Use Instant (or OffsetDateTime) for a moment in time, and LocalDate for a calendar day that has no time zone, such as a birthday.

Optional fields and PATCH

With a record, a missing field becomes null (or 0 for a primitive). That makes "field not sent" and "field sent as null" look the same, which matters for PATCH requests. Prefer wrapper types such as Integer for optional numbers, and keep partial updates simple (a separate UpdateBookRequest with nullable fields) unless you truly need JSON Patch.

DTO versus entity

An entity is the object your database layer persists. It carries internal fields (a password hash, an audit column, a version counter), lazy collections and sometimes back-references to its parent. Returning it directly is tempting and almost always a mistake:

  • Leaks: every field you add to the table later is public the next day.
  • Lock-in: you cannot rename a column without breaking clients.
  • Failures: lazy relationships throw when Jackson touches them after the transaction ends, and bidirectional links recurse forever.
  • Over-posting: accepting an entity as @RequestBody lets a client set fields they should never control, such as admin or id.

The fix is a DTO for each direction: a request DTO with exactly the fields a client may send, and a response DTO with exactly the fields a client may see. Mapping between them is a few lines of code, written by hand or generated by a mapper library.

Java Entity in, DTO out

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The entity version exposes the password hash, the admin flag and the version counter. The DTO version exposes two fields. The request DTO simply has nowhere to put the admin value, so the over-posting attempt is dropped.

Strings, bytes and other bodies

JSON is the default, not the only choice. A method that returns String with text/plain, a byte[], a Resource or a ResponseEntity<byte[]> uses a different converter. Content negotiation (the Accept header, or produces on the mapping) chooses between them when several can write the same type. Add jackson-dataformat-xml and the same controller can answer application/xml with no code changes.

Keep request and response DTOs next to the controller that uses them, name them by role (CreateBookRequest, BookResponse) and never reuse one class for both directions. When the two drift apart, you will be glad they were separate.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does Spring use to turn a JSON request body into the object declared on a @RequestBody parameter?

    Spring keeps an ordered list of message converters and picks the first one that can read the given content type into the given Java type. For JSON this is the Jackson converter.
  2. 2. A client posts JSON with a Content-Type that no converter can read. Which status does Boot return?

    When no converter can read the request body, Spring Web answers 415. A malformed or mistyped JSON body gives 400 instead.
  3. 3. Why should a controller avoid returning a database entity directly?

    Every field on the entity becomes part of the public API, lazy relations can fail during serialization, and a request entity lets clients set fields they should not control. A DTO exposes only what you choose.
  4. 4. Why should you configure Boot's Jackson with properties or customizers rather than calling new ObjectMapper() in a controller?

    Boot builds one shared mapper with ISO dates, modules and your spring.jackson.* settings. A private mapper behaves differently and makes the API inconsistent.

Summary

  • @RequestBody and @RestController rely on HttpMessageConverters; Jackson handles JSON, chosen by Content-Type and Accept.
  • Records make compact, immutable DTOs that Jackson reads and writes without extra code.
  • Boot's shared mapper writes ISO-8601 dates and ignores unknown fields; tune it through spring.jackson.* or customizer beans.
  • Send dates as ISO strings: Instant for moments, LocalDate for calendar days.
  • Use separate request and response DTOs instead of entities to avoid leaks, lazy-loading errors and over-posting.
  • Boot 4 uses Jackson 3 (tools.jackson); annotations such as @JsonProperty stay in com.fasterxml.jackson.annotation.

Next: Bean Validation.