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

Java Gson Maven dependency

This is a Maven dependency for Gson.

Java Gson Serializing Null Values Example

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


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;

    public String toString() {
        return new StringBuilder().append("User{").append("First name: ")
            .append(firstName).append(", Last name: ")

public class GsonSerializeNulls {

    public static void main(String[] args) {

        GsonBuilder builder = new GsonBuilder();


        Gson gson = builder.create();

        UserDetails user = new UserDetails();

        String json = gson.toJson(user);


Free Spring Boot Tutorial - 5 Hours Full Course

Watch this course on YouTube at Spring Boot Tutorial | Fee 5 Hours Full Course