Serializing Null Fields
The default behaviour implemented in Gson is that null object fields are ignored.
Means Gson object 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 using the GsonBuilder.
Here's how you would configure a Gson instance to output null:
Gson gson = new GsonBuilder().serializeNulls().create();
Here is an example showing how to force serialization of null values with GSON:
/** * @author TutorialToUs.com */ package com.tutorialtous.gson; import com.google.gson.Gson; import com.google.gson.GsonBuilder; public class SerializeNullExample { public static void main(String args[]) { Player obj = new Player(); obj.age = 29;obj.name = "Alex"; obj.gender = null; Gson gson = new Gson(); System.out.println("Without NullSerialize:"+gson.toJson(obj)); GsonBuilder builder = new GsonBuilder(); gson = builder.serializeNulls().create(); System.out.println("With NullSerialize:"+gson.toJson(obj)); } }
OutPut:- Without NullSerialize:{"name":"Alex","age":29,"gamesplayed":[]} With NullSerialize:{"name":"Alex","gender":null,"age":29,"gamesplayed":[]}
Once serializeNulls() has been
called the Gson instance created by the GsonBuilder will include
null fields in the serialized JSON.
The output from the
above example would be:
{"name":"Alex","gender":null,"age":29,"gamesplayed":[]}
Notice how the gender field is null.