Java Gson Serializing Null Values Example

Gson by default does not serialize fields with null values to JSON. If a field in a Java object is null, Gson excludes it. We can force Gson to serialize null values via the GsonBuilder by using serializeNulls() method.
Gson is a Java serialization/deserialization library to convert Java Objects into JSON and back. Gson was created by Google for internal use and later open-sourced.
Check out the complete Gson tutorial at https://www.javaguides.net/p/google-gson-tutorial.html.

Java Gson Maven dependency

This is a Maven dependency for Gson.
<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.2</version>
</dependency>

Java Gson Serializing Null Values Example

The example shows how to serialize null values.
package net.javaguides.gson;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

class UserDetails {

    private String firstName;
    private String lastName;

    public UserDetails() {};

    public UserDetails(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    @Override
    public String toString() {
        return new StringBuilder().append("User{").append("First name: ")
            .append(firstName).append(", Last name: ")
            .append(lastName).append("}").toString();
    }
}

public class GsonSerializeNulls {

    public static void main(String[] args) {

        GsonBuilder builder = new GsonBuilder();

        builder.serializeNulls();

        Gson gson = builder.create();

        UserDetails user = new UserDetails();
        user.setFirstName("Tony");

        String json = gson.toJson(user);
        System.out.println(json);
    }
}
Output:
{"firstName":"Tony","lastName":null}

Reference

Comments