Video in progress

Junior 🌱 Spring

How does a Java object returned by a controller turn into JSON?

Spring MVC passes the object a @RestController method returns to an HttpMessageConverter. Jackson is on the classpath, Boot sets up MappingJackson2HttpMessageConverter, and it turns the object into JSON through its getters.

📖 Answer

In short:

  1. The method returned a BookDto.
  2. @RestController = @Controller + @ResponseBody, so the result is the response body, not a view.
  3. Spring looks for a suitable converter based on the request's Accept header.
  4. The Jackson converter writes JSON with the ObjectMapper and sets Content-Type: application/json.

spring-boot-starter-web already includes Jackson, so you don't need to add anything.

public record BookDto(Long id, String title, LocalDate published) {}
// -> {"id":1,"title":"Sariq devni minib","published":"1968-01-01"}

Good to know:

  • in a plain class a field is visible only through a public getter; with no getter, the field doesn't make it into the JSON. Records don't have this problem;
  • Boot writes LocalDate in ISO format because the jackson-datatype-jsr310 module is registered automatically;
  • if Accept: application/xml is sent and there's no XML converter, you get 406 Not Acceptable.

With @RequestBody the same thing works in the opposite direction: JSON -> Java object.