Java Jackson Ignore Null Example

1. Introduction

Jackson, a widely used Java library for processing JSON, provides various ways to customize the serialization and deserialization process. One common requirement is to ignore or skip fields with null values during serialization, ensuring the resulting JSON is clean and concise. Jackson offers an easy configuration for this, which we will explore in this blog post.

2. Example Steps

1. Add the necessary Jackson library dependencies to your project.

2. Create a Java class (POJO).

3. Set some fields of the POJO to null and others to non-null values.

4. Configure Jackson's ObjectMapper to ignore fields with null values during serialization.

5. Serialize the object to a JSON string and display it.

3. Java Jackson Ignore Null Example

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JacksonIgnoreNullExample {

    public static void main(String[] args) {
        try {
            Person person = new Person();
            person.setName("John");
            // We're not setting the age, so it remains null

            ObjectMapper mapper = new ObjectMapper();
            // Configure ObjectMapper to skip null fields
            mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

            String jsonData = mapper.writeValueAsString(person);
            System.out.println(jsonData);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    static class Person {
        private String name;
        private Integer age;

        // Standard getters and setters omitted for brevity
        public String getName() { return name; }
        public void setName(String name) { this.name = name; }
        public Integer getAge() { return age; }
        public void setAge(Integer age) { this.age = age; }
    }
}

Output:

{"name":"John"}

4. Step By Step Explanation

1. We define a simple Person class with two fields: name and age. For this example, the age field is set as an Integer (wrapper class) so it can be null.

2. In the main method, we instantiate a Person object and set only the name field, leaving the age field as null.

3. We then initialize Jackson's ObjectMapper.

4. To make the ObjectMapper ignore fields with null values during serialization, we use the setSerializationInclusion(JsonInclude.Include.NON_NULL) method. This configuration ensures that any field with a null value is not included in the resulting JSON.

5. We serialize the Person object into a JSON string using writeValueAsString() and print the output.

6. As observed in the output, only the name field appears in the JSON, and the age field, being null, is omitted.

By using Jackson's setSerializationInclusion method with the JsonInclude.Include.NON_NULL configuration, we can effortlessly filter out null values from the serialization output, leading to cleaner JSON representations.


Comments