问题描述
如何在JSON响应(视图)中包含Java对象的所有字段,而不在该Java对象的每个字段上指定 @JsonView
?
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?
编辑:我需要这个来实现不使用另一个外部库。
I need this to achieve with out the use of another external library.
推荐答案
这是 @JsonView
的常见问题。注释仅适用于方法和属性,因此您不能只注释整个类并包含所有属性。
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.
我将假设您在Spring中使用它。这种行为是由于Spring选择在ObjectMapper中默认禁用所有属性的包含。因此,只包含 @JsonView
带注释的属性,而其他属性则不包含。
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.
您可以更改通过将 MapperFeature.DEFAULT_VIEW_INCLUSION
设置为 true
。像这样:
You can change this by setting MapperFeature.DEFAULT_VIEW_INCLUSION
to true
. Like this:
普通Java:
mapper.configure(MapperFeature.DEFAULT_VIEW_INCLUSION, true);
Spring Boot(将此添加到application.properties):
Spring Boot (add this to application.properties):
spring.jackson.mapper.default-view-inclusion=true
默认情况下,这种方式在JSON seralization期间将包含所有属性,您可以使用 @JsonInclude
和其他Jackson注释来控制包含和排除。
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.
这篇关于JsonView对象的所有字段的注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!