Jackson: Ignore null and empty fields

This article discusses options to ignore null and empty fields during serialization to JSON using Jackson 2.x.

By default, Jackson 2.x includes null and empty object fields while serializing to JSON. Sometimes, it is desirable to ignore such fields. You can do that by following any of the following two options:

  1. Annotate the class or the fields with @JsonInclude
  2. Instruct the object mapper to skip the null fields

 

Option 1: Annotating with @JsonInclude

Jackson 2.x 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 valid values:

  1. Include.NON_NULL

    Indicates that only non-null properties should be serialized.

  1. Include.NON_EMPTY

    Indicates that only non-null and non-empty properties should be serialized. This acts as a superset of Include.NON_NULL.

  1. Include.NON_DEFAULT

    Indicates that only properties that have been set after the class object is created should be serialized. This ignores final and default fields during serialized. Default fields, in this context, are those that have values different than those assigned during the object creation. In most cases, this acts as superset of Include.NON_EMPTY.

  1. Include.ALWAYS

    Indicates that all properties should be serialized, irrespective of their values.

As a developer, you can dictate and control serialization of your classes by annotating them with @JsonInclude. It is important to note that object mapper cannot override these class level annotations. Also, it is equally important to note that these annotations are effective only if you use Jackson to serialize the objects. These annotations have no effect on other serialization libraries.

For sake of demonstrations, we use the Employee class shown below, as the model class and use it to demonstrate how to ignore null and empty fields during serialization.

Employee class

Main

Output

Skipping null and empty fields

To skip null and empty fields, we annotate the class as shown below:

Output after annotating Employee class

Note: @JsonInclude can be used with individual fields as well, instead of the entire class. It will affect only the annotated field(s).
 

Option 2: Instructing the Object Mapper

The Jackson Object Mapper can take serialization option that controls the serialization process. You can set the option by calling setSerializationInclusion() and pass in the desired JsonInclude serialization option.

Note: Mapper cannot override the Jackson annotations on the class

Main

Output

 


 

Leave a Reply

avatar
300
  Subscribe  
Notify of