Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – Black Friday 2026 – NPI EA – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

1. Introduction

When we work with Java objects and need to convert them into JSON format, it’s crucial to handle null values appropriately. Omitting null values from the JSON output might not align with our data requirements, especially when data integrity is paramount.

In this tutorial, we’ll delve into effective methods for including null values during JSON serialization in Java.

2. Use Case Scenario: Customer Management System

Let’s consider that we’re developing a customer management system where each customer is a Java object with attributes like name, email, and age. Moreover, some customers may lack email addresses.

When serializing customer data into JSON for storage or transmission, including null values for missing email addresses is crucial to maintain data consistency.

For the sake of completeness, let’s define the Customer class used in our examples:

public class Customer {
    @JsonProperty
    private final String name;
    @JsonProperty
    private final String address;
    @JsonProperty
    private final int age;

    public Customer(String name, String address, int age) {
        this.name = name;
        this.address = address;
        this.age = age;
    }

    // ...
}

Here, we define the Customer class which includes fields for name, address, and age, initialized through a constructor method. The toString() method also provides a string representation of the object in a JSON-like format for easy debugging.

Please note that including @JsonProperty annotations ensures that all relevant fields are accurately serialized into the JSON output, including null values when applicable.

3. Using Jackson Library

Jackson, a renowned Java library for JSON processing, typically excludes null values from JSON output by default. However, we can leverage Jackson’s annotations to include null values explicitly:

String expectedJson = "{\"name\":\"John\",\"address\":null,\"age\":25}";
Customer obj = new Customer("John", null, 25);

@Test
public void givenObjectWithNullField_whenJacksonUsed_thenIncludesNullValue() throws JsonProcessingException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.setSerializationInclusion(JsonInclude.Include.ALWAYS);
    String json = mapper.writeValueAsString(obj);
    assertEquals(expectedJson, json);
}

In this method, we begin by establishing the expectedJson string. Subsequently, we instantiate a Customer object with values John, null, and 25.

Moving forward, we configure an ObjectMapper instance to consistently include null values during serialization by invoking the setSerializationInclusion() method with the parameter JsonInclude.Include.ALWAYS. This meticulous setup ensures that even if the address is null, it’s accurately represented in the resulting JSON output.

Lastly, we use the assertEquals() method to verify that the json string matches the expectedJson.

4. Using Gson Library

Gson is an alternative Java library that can be used for JSON serialization and deserialization. It offers similar options to include null values explicitly. Let’s see an example:

@Test
public void givenObjectWithNullField_whenGsonUsed_thenIncludesNullValue() {
    Gson gson = new GsonBuilder().serializeNulls().create();
    String json = gson.toJson(obj);
    assertEquals(expectedJson, json);
}

Here, we employ the GsonBuilder to set up a Gson instance using the serializeNulls() method. This configuration ensures that null values are incorporated during serialization, ensuring precise representation in the resulting JSON output, even if the address field is null.

5. Conclusion

In conclusion, it’s essential to handle null values appropriately when working with Java objects and converting them into JSON format.

In this tutorial, we learned how to do it during JSON serialization.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

Course – Black Friday 2026 – NPI EA – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW