Skip to content

Gson – Serialize HashMap null entries

Gson – serialize HashMap null entries example shows how to serialize HashMap entries with null values using the Gson library in Java.

How to serialize null HashMap entries?

By default, the Gson library ignores the HashMap null entries when we serialize it. These null entries are not included in the output JSON. See the below given example to understand it better.

Output

As we can see from the output, the “parkingLot” property is not serialized because it contained a null value. This is the default behavior of the Gson library where it ignores map null entries.

In order to include the map null entries, we need to create the Gson object using GsonBuilder class along with calling the serializeNulls method as given below.

Output

As we can see from the output, the null entry is serialized this time.

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

About the author

Leave a Reply

Your email address will not be published.