Ignoring Null Fields with @JsonInclude

The @JsonInclude annotation is used to specify whether fields with null values should be included in the JSON output. By applying this annotation to fields or at the class level, we can control how Jackson handles null fields during serialization.

Ignore null Fields at Class Level

By placing @JsonInclude annotation with include.NON_NULL on class, all fields with null value will be ignored during serialization.

    @JsonInclude(JsonInclude.Include.NON_NULL)
    private static class Person {

        private Long id;
        private String name;
        private String dateOfBirth;
        private String city;

    }
    public static void main(String[] args) throws IOException {

        Person person = new Person(1L, "Alice", null, null);

        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(person);

        System.out.println("Serialized Person: " + json);
    }

In this example, both dateOfBirth and city are null, they are not included in the serialized json string.

Serialized Person: {"id":1,"name":"Alice"}

Ignore null Fields at Field Level

We can use @JsonInclude annotation with include.NON_NULL at field level to ignore a specific null field. Let’s see an example:

    
    private static class Person {

        private Long id;
        private String name;
        @JsonInclude(JsonInclude.Include.NON_NULL)
        private String dateOfBirth;
        private String city;

    }
    public static void main(String[] args) throws IOException {

        Person person = new Person(1L, "Alice", null, null);

        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(person);

        System.out.println("Serialized Person: " + json);
    }

From the output, we know that the dateOfBirth field has been ignored because there is @JsonInclude(JsonInclude.Include.NON_NULL) annotated on it. the annotation is not on city field, so city field with null value is included.

Serialized Person: {"id":1,"name":"Alice","city":null}

Read More