如果顶级字段的所有嵌套字段都为空,则Jackson会忽略顶级字段的序列化

时间:2017-03-06 10:05:47

标签: java serialization jackson

我正在使用Jackson ObjectMapper来序列化POJO。我在POJO中嵌套了字段。例如:序列化类MyClass

public class MyClass {
    private A a;
    private int i;
    //getters and setters
}

public class A {
    private String s;
    //getters and setters
}

我希望如果String snull,则整个属性A不会被序列化。也就是说,如果String snull,我希望输出为: {"myClass":{"i":10}}

但我得到{"myClass":{"A":{},"i":10}}作为输出。

我已将NON_EMPTY设置为序列化包含(mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY)),但它无法解决问题

3 个答案:

答案 0 :(得分:0)

AFAIK你不能用标准注释做到这一点,但是你应该以这种方式改变MyClass.getA()方法。

  public A getA() {
    if (a.getS() == null)
      return null;
    return a;
  }

答案 1 :(得分:0)

你只需添加@JsonInclude(JsonInclude.Include.NON_NULL)

@JsonInclude(JsonInclude.Include.NON_NULL)
public class MyClass   extends Serializable {
    private A a;
    private int i;
    //getters and setters
}

public class A  extends Serializable{
    private String s;
    //getters and setters
}

答案 2 :(得分:0)

在所需的类中生成hashCode()equals()

public class A  extends Serializable{
    private String s;
    // getters and setters
    // hashCode() and equals()
}

在父类中设置一个Include.CUSTOM

@JsonInclude(value = Include.CUSTOM, valueFilter = A.class)
public class MyClass extends Serializable {
    private A a;
    private int i;
    //getters and setters
}

所有空对象将被排除,输出将为:{"myClass":{"i":10}}