我正在使用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
,因此不想改变该过程。是否有一种方式可以使 Jackson 将具有 null 字段的对象视为 null,并使用自定义序列化程序?我看到了针对特定类型的对象使用自定义序列化程序的示例,但我需要适用于任何对象的程序。