![](/img/trans.png)
[英]Jackson ignore serialization of top-level field if all its nested fields are null
[英]Jackson JSON serialization: How to ignore a nested object when all its fields are null?
我正在使用 Jackson 並且我有一些 JSON 模式對象設置如下:
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class Person {
String name;
Child child = new Child();
Sibling sibling = new Sibling();
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Child getChild() {
return child;
}
public void setChild(Child child) {
this.child = child;
}
public Sibling getSibling() {
return sibling;
}
public void setSibling(Sibling sibling) {
this.sibling = sibling;
}
}
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class Child {
String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class Sibling {
String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
我試圖忽略所有為空或空的字段,這很好用。 但我也想忽略字段全部為空或空的對象。 例如:
Person person = new Person();
person.setName("John Doe");
ObjectMapper mapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(person);
生成的 JSON 字符串是{"name":"John Doe","child":{},"sibling":{}}
,但我希望它是{"name":"John Doe"}
。 創建Person
時需要初始化Child
和Sibling
,所以我不想更改它。 有沒有辦法讓傑克遜使用自定義序列化程序將具有空字段的對象視為空? 我見過為特定類型的對象使用自定義序列化程序的示例,但我需要一個適用於任何對象的示例。
您可以以一種可能更簡單的方式來實現此目的,而無需為Person
或Child
和Sibling
使用CUSTOM
定義序列化程序,而使用CUSTOM
include並將字段類型作為過濾器傳遞。
首先,為Child
和Sibling
定義正確的equals
方法。 然后,要過濾與其默認構造函數將返回的嵌套對象相等的嵌套對象,請在Person
注釋相關的獲取器,如下所示:
@JsonInclude(value = JsonInclude.Include.CUSTOM, valueFilter = Child.class)
public Child getChild() {
return child;
}
@JsonInclude(value = JsonInclude.Include.CUSTOM, valueFilter = Sibling.class)
public Sibling getSibling() {
return sibling;
}
將valueFilter
設置為上面的Child.class
的作用是使用默認構造函數Child emptyChild = new Child()
創建一個對象,然后確定應該序列化另一個對象Child child
來檢查emptyChild.equals(child)
是否為false
在您的情況下,我認為在序列化程序級別忽略空值就足夠了:
mapper.setSerializationInclusion(Include.NON_EMPTY);
mapper.setSerializationInclusion(Include.NON_NULL);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.