4

I have read questions like these @JsonInclude to ignore null values. This works for me for regular fields within an entity but not for Collections. In case of empty Collections within an entity, Json serialisation gives a null value.

How does one do a equivalent ignore for collections ?

Community
  • 1
  • 1
HopeKing
  • 3,317
  • 7
  • 39
  • 62

2 Answers2

8

Try with the annotation

@JsonInclude(Include.NON_EMPTY)
private Collection field;
Abdullah Khan
  • 12,010
  • 6
  • 65
  • 78
Zeromus
  • 4,472
  • 8
  • 32
  • 40
  • It works - in my version it is @JsonInclude(JsonInclude.Include.NON_EMPTY). My bad, I was thinking of them as null collection rather than an empty collection. – HopeKing May 17 '17 at 08:12
2

Since the Jackson 2.x it provides @JsonInclude annotation that controls serialization of a class as a whole or its individual fields based on their values during serialization. It recognizes following annotations as:

Include.NON_NULL Indicates that only non-null properties should be serialized.

Include.NON_EMPTY Indicates that only non-null and non-empty properties should be serialized. This is actually the superset of Include.NON_NULL

Hence over a collection Include.NON_EMPTY will work like

@JsonInclude(Include.NON_EMPTY)
private Collection field;

or you can put it over the class to impact upon the whole model like

@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class Foo {
}
Shafin Mahmud
  • 3,831
  • 1
  • 23
  • 35