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
package com.tutorialtous.gson;
public class SerializeNullExample {
  public static void main(String args[]) {
    Player obj = new Player();
    obj.age = 29; = "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));
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:
Notice how the gender field is null.

Copyright © 2018-2020 TutorialToUs. All rights reserved.