How to not send an empty collection in jackson

后端 未结 2 1301
攒了一身酷
攒了一身酷 2021-01-01 14:09

I have an object that is curently being serialized to:

{
  \"label\" : \"label\",
  \"proxyIds\" : [ ],
  \"childIds\" : [ 161, 204, 206, 303, 311 ],
  \"act         


        
相关标签:
2条回答
  • 2021-01-01 14:13

    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;
    
        ...
    }
    
    0 讨论(0)
  • 2021-01-01 14:30

    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

    0 讨论(0)
提交回复
热议问题