Home » Jackson Ignore Null Fields

Jackson Ignore Null Fields

by Online Tutorials Library

Jackson Ignore Null Fields

In this section, we will understand how we can ignore the null fields at the time of serializing a Java class by using Jackson.

We can ignore null fields at class level, field level or globally. Let’s understand each one of them one by one.

Ignore null fields at class level

In order to ignore null fields at the class level, we use the @JsonInclude annotation with include.NON_NULL. Let’s take an example to understand how we can use @JsonInclude annotation to ignore the null fields at the class level.

IgnoreNullFieldExample1.java

Output:

Jackson Ignore Null Fields

Ignore specific null field

Here, we use @JsonInclude annotation with include.NON_NULL at field level to ignore a specific null field. Let’s take an example to understand how we can use @JsonInclude annotation to ignore a specific null field.

IgnoreNullFieldExample2.java

Output:

Jackson Ignore Null Fields

Ignore null fields globally

Here, we use JsonInclude.Include.NON_NULL on the ObjectMapper class to configure the behavior of ignoring null fields globally. We use the setSerializationInclusion() method with Include.NON_NULL in the following way:

Let’s take an example to understand how we can ignore null fields globally by using the setSerializationInclusion() method.

IgnoreNullFieldExample3.java

Output:

Jackson Ignore Null Fields

All the above methods are used for ignoring null fields, where each method is used in different cases.


You may also like