Javatpoint Logo
Javatpoint Logo

Serialize Fields Based on Custom Criteria in Jackson

By using Jackson, we can serialize only those fields that meet specific custom criteria. Sometimes, we need to serialize a field of type int only when its value is positive. If its value is negative, we will skip it entirely.

Control the serialization process by using the Jackson filter

Jackson Filter plays an important role in controlling the serialization. We use the @JsonFilter annotation. The @JsonFilter annotation is used to define the custom filter on our entity.

We use the JsonFilter annotation in the following way:

We use the following steps to serialize the fields based on the custom criteria:

  1. Define the filter on our entity class using the @JsonFilter
  2. Define the custom PropertyFilter.
  3. Hook the filter into the ObjectMapper.
  4. Serialize the entity.

Let's take an example in which we use the above steps to serialize the fields based on the custom criteria.

JsonFilterExample1.java

Output:

Serialize Fields Based on Custom Criteria in Jackson

Let's take another example to understand how we can skip the complete Object based on some condition. We skip all those objects where the isHidden property will be equal to true.

We use the following steps to skip the complete Object for serializing by using JsonFilter.

  1. First, we create Hidable interface by using the @JsonIgnoreProperties({"hidden", "isHidden"}).
  2. Next, we create two classes, i.e., College and Address, which implement the Hidable We use the @JsonIgnoreProperties({"hidden", "isHidden"}) annotation to make sure that the isHidden property or hidden properties are not included in JSON.
  3. We create a custom serializer, i.e., HidableJavaSerializer, for skipping the Object at the time or serializing.
  4. We use the BeanSerializerModifier for injecting the default serializer in our custom HidableJavaSerializer.

Let's implement the code for all the above points which we mentioned above.

Hidable.java

HidableJavaSerializer.java

JsonFilterExample2.java

Output:

Serialize Fields Based on Custom Criteria in Jackson





Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA