JsonView annotation for all fields of a object

前端 未结 2 1941
南方客
南方客 2021-01-15 09:21

How can I include all fields of Java object to the JSON response (view) with out specify @JsonView on every field of that Java object?

Edit: I need thi

相关标签:
2条回答
  • 2021-01-15 09:51

    Since Jackson 2.9, the @JsonView annotation can now be applied to the class level to have the behavior you are asking for.

    https://github.com/FasterXML/jackson/wiki/Jackson-Release-2.9

    Allow use of @JsonView on classes, to specify Default View to use on non-annotated properties.

    @JsonView(MyView.class);
    public class AllInView {
    
        // this will be in MyView
        private String property1;
    
        // this will be in MyView
        private String property2;
    
        // this will be in DifferentView
        @JsonView(DifferentView.class)
        private String property3;
    
    }
    
    0 讨论(0)
  • 2021-01-15 10:01

    This is a common problem with @JsonView. The annotation is applicable only on methods and properties, so you cannot just annotate the whole class and include all properties.

    I'm going to assume you are using this with Spring. That behavior is due to the fact that Spring chooses to disable inclusion of all properties by default in the ObjectMapper. Because of that, only @JsonView annotated properties will be included, while other properties will not.

    You can change this by setting MapperFeature.DEFAULT_VIEW_INCLUSION to true. Like this:

    Plain Java:

    mapper.configure(MapperFeature.DEFAULT_VIEW_INCLUSION, true);
    

    Spring Boot (add this to application.properties):

    spring.jackson.mapper.default-view-inclusion=true
    

    This way by default all properties will be included during JSON seralization, and you can use @JsonInclude and other Jackson annotations to control inclusions and exclusions.

    0 讨论(0)
提交回复
热议问题