Skip to content

Gson – Serialize Null Values

Gson – Serialize Null Values example shows how to serialize null field values using the Gson library in Java. By default, Gson does not serialize class fields that have null values.

How to serialize null field values in Gson?

The default behavior of Gson skips the fields that have null values in output while serializing. That means, all the class fields having null values are omitted from the JSON when we serialize the object of that class.

In the below given example, when we try to serialize the object of the Student class, the last name field will be omitted from the JSON because it is null.

Output

As we can see from the output, the lastName field was omitted in the JSON because it was null.

We can easily change this default behavior by creating the Gson object using the GsonBuilder instead of the constructor and calling the serializeNulls method.

Calling the serializeNulls method will make Gson include the null fields when we serialize an object to JSON as given below.

Output

As we can see from the output, this time Gson serialized the lastName field even though it was null.

Please let me know your views in the comments section below.

About the author

Leave a Reply

Your email address will not be published.