3

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

freedev
  • 25,946
  • 8
  • 108
  • 125
Nitesh Kumar
  • 789
  • 1
  • 5
  • 11
  • Possible duplicate of [How to tell Jackson to ignore a field during serialization if its value is null?](http://stackoverflow.com/questions/11757487/how-to-tell-jackson-to-ignore-a-field-during-serialization-if-its-value-is-null) – Arpit Aggarwal Mar 06 '17 at 17:00
  • I don't think this question is a duplicate because it regards nested objects. The referred question does not handle it, and the solution there does not suffice. – Stempler Apr 10 '19 at 08:23

3 Answers3

1

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;
  }
freedev
  • 25,946
  • 8
  • 108
  • 125
0

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
}
Younes Ouchala
  • 300
  • 1
  • 4
  • 15
0

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}}

Stempler
  • 1,309
  • 13
  • 25