Video in progress
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:
- The method returned a
BookDto. @RestController=@Controller+@ResponseBody, so the result is the response body, not a view.- Spring looks for a suitable converter based on the request's
Acceptheader. - The Jackson converter writes JSON with the
ObjectMapperand setsContent-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
LocalDatein ISO format because thejackson-datatype-jsr310module is registered automatically; - if
Accept: application/xmlis sent and there's no XML converter, you get406 Not Acceptable.
With @RequestBody the same thing works in the opposite direction: JSON -> Java object.
Sign up to mark studied questions and save your progress.