Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to not send an empty collection in jackson

Tags:

I have an object that is curently being serialized to:

{   "label" : "label",   "proxyIds" : [ ],   "childIds" : [ 161, 204, 206, 303, 311 ],   "actionIds" : [ 157, 202 ], } 

That proxyIds is an empty (not null) collection in the java object.

How do I configure Jackson to not include that object in the json at all?

I want behaviour similar to "unwrapped" collections in xml/soap where if the collection is empty it is not included. I do not need to distinguish between null and empty collection and want to reduce the size of the json payload.

like image 843
Michael Wiles Avatar asked Jan 17 '12 17:01

Michael Wiles


People also ask

How do I ignore empty values in JSON response?

You can ignore null fields at the class level by using @JsonInclude(Include. NON_NULL) to only include non-null fields, thus excluding any attribute whose value is null. You can also use the same annotation at the field level to instruct Jackson to ignore that field while converting Java object to json if it's null.

Can you have an empty array in JSON?

JSON data has the concept of null and empty arrays and objects.


2 Answers

Since Jackson 2.0.0 (25-Mar-2012), you can also use the @JsonInclude annotation to control this on a per-field or per-class basis.

public class MyObject {      @JsonInclude(Include.NON_EMPTY)     private List<Integer> proxyIds;      ... } 
like image 59
pimlottc Avatar answered Sep 28 '22 03:09

pimlottc


This may be a long shot but how about using Inclusions and defining NON_DEFAULT as the inclusion property. The docs say:

"Value that indicates that only properties that have values that differ from default settings (meaning values they have when Bean is constructed with its no-arguments constructor) are to be included."

So if the default value is an empty array it should skip it.

Something like:

ObjectMapper mapper = new ObjectMapper(); mapper.getSerializationConfig().setSerializationInclusion(Inclusion.NON_DEFAULT);   public class Test {      String[] array = { };      .... } 

http://jackson.codehaus.org/1.1.2/javadoc/org/codehaus/jackson/map/annotate/JsonSerialize.Inclusion.html

like image 25
Usman Ismail Avatar answered Sep 28 '22 02:09

Usman Ismail