我有一个包含很多 pojo 字段的 pojo,我使用 Jackson 将它们序列化。 例如:
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class FOO {
private BOO boo = new BOO();
private GOO goo = new GOO();
// Getters & setters
}
内部类BOO定义例如:
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class BOO {
private AAA aaa = new AAA();
private BBB bbb = new BBB();
// Getters & setters
}
现在,我希望仅当 BOO 类的所有字段(在我的示例中为 aaa、bbb)都为 null 或为空时,才将 BOO 类序列化为 JSON。 我读了here , 和 here ,我可以使用 JsonSerializer 和 BeanSerializerModifier 来完成。
但是,我想知道是否有更简洁的方法来做到这一点,而无需为我要处理的每个自定义字段定义额外的类。 例如,如果我能以某种方式为我的 BOO 对象覆盖并实现 Jackson isEmpty() 方法(实现一些 Jackson 接口(interface)),那就太好了。
有没有更简单的方法呢?
编辑:
我希望能够执行以下操作,而不必检查空值:
foo.getBoo().getAaa();
谢谢。
最佳答案
这很容易通过 getter 方法中的逻辑来实现:
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class FOO {
private BOO boo = new BOO();
private GOO goo = new GOO();
public BOO getBoo() {
//replace if block with "empty" check logic
if(this.boo.getAaa() == null || this.boo.getBbb() == null) {
return this.boo;
}
return null;
}
}
结合@JsonInclude(JsonInclude.Include.NON_EMPTY)
指令,字段为null时不包含
当然,正如您提到的,您可以将 isEmpty()
添加到 BOO
并从 getter 方法中调用它。
关于java - Jackson - 在不使用 JsonSerializer 和 BeanSerializerModifier 的情况下定义空字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52478701/