How to tell Jackson to ignore a field during serialization if its value is null?

2021-6-3 anglehua

How can Jackson be configured to ignore a field value during serialization if that field's value is null.

For example:

public class SomeClass {
   // what jackson annotation causes jackson to skip over this value if it is null but will 
   // serialize it otherwise 
   private String someValue; 
}

To suppress serializing properties with null values using Jackson >2.0, you can configure the ObjectMapper directly, or make use of the @JsonInclude annotation:

mapper.setSerializationInclusion(Include.NON_NULL);

or:

@JsonInclude(Include.NON_NULL)
class Foo
{
  String bar;
}

Alternatively, you could use @JsonInclude in a getter so that the attribute would be shown if the value is not null.

A more complete example is available in my answer to How to prevent null values inside a Map and null fields inside a bean from getting serialized through Jackson.



With Jackson > 1.9.11 and < 2.x use @JsonSerialize annotation to do that:

@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)



采集自互联网,如有侵权请联系本人

Powered by emlog 京ICP备15036472号-3 sitemap