Configuring Gson to serialize objects with fields having null value

Whenever we serialize a java object to JSON using Gson framework, by default fields with null values are ignored.

As shown in the below code

Main code


public class GsonDemo7 {
    public static void main(String[] args) {
        Student student = new Student();
        Gson gson = new Gson();
        String result = gson.toJson(student);

In the above code Student object is created. We have set values for all its field except date field which is null.

When we serialize the Student object using the gson instance having default configurations, it will ignore the date field. As shown in the below output.

The output of the above code will be



To change the default configuration and serialize the fields with null values. We will modify the above code as shown below

Modified Main Code

1  import;
2  import;
4  public class GsonDemo7 {
5   public static void main(String[] args) {
6       Student student = new Student();
7       student.setId(1);
8       student.setName("name1");
9       student.setRollnum(100);
10      student.setDate(null);
12      GsonBuilder gsonBuilder = new GsonBuilder();
13      Gson gson = gsonBuilder.serializeNulls().create();
14      String result = gson.toJson(student);
15      System.out.println(result);
16  }
17 }

At line 12, we create GsonBuilder instance.

At line 13, we tell the GsonBuilder to create a Gson instance that will serialize fields with null values by calling the “serializeNulls” function.

Now whenever we call toJson function with an object having fields with null value, those fields will also be serialized.

The output of the above code is as shown below



Leave a Reply