@ResponseBody, ResponseEntity Spring returns an object as JSON

I am using Spring version 4 (Spring data), I want to return Object as JSON, I am surprised that the following code worked even without annotating the user class with xmlRootElement:

@RequestMapping(value = "/resources/users", method = RequestMethod.GET)
public ResponseEntity<User> getUserByLogonId(OAuth2Authentication auth) {

    String userLogonId = ((org.springframework.security.core.userdetails.User) auth.getUserAuthentication()
            .getPrincipal()).getUsername();
    UsersServices usersServices = new UsersServicesImpl(usersOperations);
    User user = usersServices.findByLogonId(userLogonId);
    HttpStatus userStatus = HttpStatus.NOT_FOUND;
    if (user != null) {
        userStatus = HttpStatus.FOUND;
    }
    return new ResponseEntity<User>(user, userStatus);
}

Can anyone explain? Is ResponseBody / ResponseEntity the job itself? when I need to annotate an object class that should be returned as JSON.

+4
source share
2 answers

@RestControlleradds annotation itself @ResponseBody. You can see it in the Github Issue

spring . :

POJO - Collection<Bookmark>, Bookmark .. , add. HTTP-, , Accept header, Spring MVC HttpMessageConverter, , POJO , Accept header, .

@RestController , @ResponseBody @Controller. , , .

,

@RequestBody @ResponseBody, spring HttpMessageConverter .

+1

xmlRootElement XML- XML. XML JSON.
@RestController, @Controller @ResponseBody . HttpMessageConverter .
@ResponseEntity HTTP (, http- ..). :

return new ResponseEntity<String>("Hello World", responseHeaders, HttpStatus.CREATED);
+1

Source: https://habr.com/ru/post/1682967/


All Articles