简体   繁体   中英

Jackson ignore serialization of top-level field if all its nested fields are null

I am using Jackson ObjectMapper to serialize a POJO. I have nested fields in the POJO. Eg: serializing class MyClass

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

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

I want that if String s is null , the entire property A does not get serialized. That is, if String s is null , I want the output to be: {"myClass":{"i":10}}

But I am getting {"myClass":{"A":{},"i":10}} as the output instead.

I have set NON_EMPTY for serialization inclusion ( mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY) ), but it doesn't solve the problem

AFAIK you cannot do this with standard annotations, but changing MyClass.getA() method in this way you should do the trick.

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

You need just to add @JsonInclude(JsonInclude.Include.NON_NULL)

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

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

Generate hashCode() and equals() in the desired class.

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

Set an Include.CUSTOM in your parent class.

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

All empty objects will be excluded and the output will be: {"myClass":{"i":10}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM