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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
package com.javacodeexamples.gsonexamples; import java.util.HashMap; import java.util.Map; import com.google.gson.Gson; public class GsonSerializeMapNullEntries { public static void main(String[] args) { Map<String, String> mapEmpValues = new HashMap<String, String>(); mapEmpValues.put("id", "EMP001"); mapEmpValues.put("name", "Bob"); mapEmpValues.put("age", "22"); mapEmpValues.put("parkingLot", null); //convert map to JSON String jsonData = new Gson().toJson(mapEmpValues); System.out.println(jsonData); } } |
Output
1 |
{"name":"Bob","id":"EMP001","age":"22"} |
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.
1 2 3 4 5 6 7 8 9 10 11 |
/* * create Gson object using the * GsonBuilder class and call the * serializeNulls method */ Gson gson = new GsonBuilder().serializeNulls().create(); //convert map to JSON String jsonData = gson.toJson(mapEmpValues); System.out.println(jsonData); |
Output
1 |
{"parkingLot":null,"name":"Bob","id":"EMP001","age":"22"} |
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.