What are the advantages of returning JSON response

2020-06-03 23:26发布

问题:

I am going through this tutorial and found we can return JSON response in Spring REST Using MappingJackson2JsonView Support over @ResponseBody Annotation.

Apparently Using @ResponseBody Annotation is very simple and easy to implement where as Using MappingJackson2JsonView Support bit complex. Any way this is my personal opinion, but I want to know what are the advantages of returning JSON response in Spring REST Using MappingJackson2JsonView Support over @ResponseBody Annotation, if there is any? Can someone explain me which one is better between them and why? When to use MappingJackson2JsonView Support and when to use @ResponseBody Annotation for returning JSON response in Spring REST?

回答1:

I think, MappingJackson2JsonView is good implementation.

But there is some advantages of ResponseBody. With Help of @ResponseBody you can return object not as property For example

class Student extends ResponseDTO{
   publci String name = "John"
}
...
@ResponseBody ResponseDTO  getStudentInfo(){
  return new Student();
}

Result will be { "name":"John" }

With MappingJackson2JsonView you must return object in property like

{
  "student": {
               "name":"John"
             }
}

with @ResponseBody you can also return result with inline object extending

 @ResponseBody getStudentInfo(){
  return new Object(){
     public String name="John"
 };
}

But this is not good implementation

Some for good implementation MappingJackson2JsonView is good. But for more functionality like as return object or return ResponseDto, ResponseBody is more usefull



回答2:

I will say that even it's a bit harder to implement, good implementation can be more flexible and powerful than @ResponseBody. For example:

Jackson2ObjectMapperBuilder provides a nice API to customize various Jackson settings while retaining Spring Framework provided default ones. It also allows to create ObjectMapper and XmlMapper instances based on the same configuration.

Both Jackson2ObjectMapperBuilder and Jackson2ObjectMapperFactoryBean define a better Jackson default configuration. For example, the DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES property set to false, in order to allow deserialization of JSON objects with unmapped properties.

But in general, it's somehow the matter of own opinion and experiences.