How does Spring auto convert objects to json for @RestController

Viewed 2734

I'm looking at code in which I'm assuming spring decides to use Jackson behind the scenes to auto convert an object to json for a @RestController

@RestController 
@RequestMapping("/api")
public class ApiController {

    private RoomServices roomServices;

    @Autowired
    public ApiController(RoomServices roomServices) {
        this.roomServices = roomServices;
    }

    @GetMapping("/rooms")
    public List<Room> getAllRooms() {
        return this.roomServices.getAllRooms();
    }
}

The Room class is just a plain java class with some fields, getters/setters. There is no Jackson or any other explicit serialization going on in the code. Although this does return json when checking the url. I tried looking through the spring documentation but I'm not quite sure what I'm looking for. What is the name for this process in spring / how does it work? I tried with just @Controller and it broke. Is this functionality coming from @RestController?

1 Answers

If you are using Spring Boot Starter Web, you can see that it's using Spring Boot Starter JSON through the compile dependencies, and Jackson is the dependency of the Start JSON library. So, you're assumption is right (Spring is using Jackson for Json convertion by default)

Spring use it's AOP mechanism to intercept the mapping methods in @Controller (you can see that @RestController is actually a @Controller with @ResponseBody), spring create a proxy object (using JDK proxy or through cglib) for the class that annotated with @Controller.

When the request flow is processing, the program who really call the mapping method will be lead to the proxy first, the proxy will invoke the real @Controller object's method and convert it's returning value to Json String using Jackson Library (if the method is annotated with @ResponseBody) and then return the Json String back to the calling program.

Related