[英]JsonView annotation for all fields of a object
如何將 Java 對象的所有字段包含到 JSON 響應(視圖)中, @JsonView
在該 Java 對象的每個字段上指定@JsonView
?
編輯:我需要在不使用另一個外部庫的情況下實現這一點。
這是@JsonView
的常見問題。 注釋僅適用於方法和屬性,因此您不能只注釋整個類並包含所有屬性。
我將假設您在 Spring 中使用它。 這種行為是由於 Spring 選擇在 ObjectMapper 中默認禁用包含所有屬性的事實。 因此,只會@JsonView
注釋的屬性,而不會包含其他屬性。
您可以通過將MapperFeature.DEFAULT_VIEW_INCLUSION
設置為true
來更改此設置。 像這樣:
普通爪哇:
mapper.configure(MapperFeature.DEFAULT_VIEW_INCLUSION, true);
Spring Boot(將此添加到 application.properties):
spring.jackson.mapper.default-view-inclusion=true
默認情況下,所有屬性都將在 JSON 序列化期間包含在內,您可以使用@JsonInclude
和其他 Jackson 注釋來控制包含和排除。
從 Jackson 2.9 開始, @JsonView
注釋現在可以應用於類級別以獲得您要求的行為。
https://github.com/FasterXML/jackson/wiki/Jackson-Release-2.9
允許在類上使用 @JsonView,以指定要在非注釋屬性上使用的默認視圖。
@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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.