Gson – Serialize NULL values

The default behavior that is implemented in Gson is that null object fields are ignored. For example, if in Employee object, we do not specify the email (i.e. email is null) then email will not be part of serialized JSON output.

Gson ignores null fields because this behavior allows a more compact JSON output format.

1. How to allow null values during serialization

To configure a Gson instance to output null, we must use serializeNulls() of GsonBuilder object.

Gson gson = new GsonBuilder()
		.serializeNulls()
		.create();

2. Demo

Let’s see the behavior of Gson while null field serialization is enabled or disabled.

This is employee class which has four fields. We will set the email field to 'null'.

public class Employee 
{
    private Integer id;
    private String firstName;
    private String lastName;
    private String email;
}

2.1. DO NOT serialize null fields

Default Gson serialization without null values in JSON output.

Employee employeeObj = new Employee(1, "Lokesh", "Gupta", null);
				
Gson gson = new GsonBuilder()
		.setPrettyPrinting()
		.create(); 

System.out.println(gson.toJson(employeeObj));
{
  "id": 1,
  "firstName": "Lokesh",
  "lastName": "Gupta"
}

2.2. Serialize null fields

Custom Gson serialization with null values included in JSON output.

Employee employeeObj = new Employee(1, "Lokesh", "Gupta", null);
				
Gson gson = new GsonBuilder()
		.setPrettyPrinting()
		.serializeNulls()
		.create(); 

System.out.println(gson.toJson(employeeObj));
{
  "id": 1,
  "firstName": "Lokesh",
  "lastName": "Gupta",
  "emailId": null
}

Clearly null field got serialized in JSON output. Drop me your question related to this Gson Serialize NULL values article.

Happy Learning !!

Reference:

Gson User Guide

Leave a Reply

0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions, and frequently asked interview questions.