Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ignore Empty Collections during Serialisation

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 ?

like image 860
HopeKing Avatar asked Nov 08 '25 23:11

HopeKing


2 Answers

Try with the annotation

@JsonInclude(Include.NON_EMPTY)
private Collection field;
like image 140
Zeromus Avatar answered Nov 10 '25 14:11

Zeromus


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 {
}
like image 44
Shafin Mahmud Avatar answered Nov 10 '25 15:11

Shafin Mahmud



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!