[英]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.