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


import com.google.gson.Gson;

public class GsonDemo7 {
    public static void main(String[] args) {
        Student student = new Student();
        student.setId(1);
        student.setName("name1");
        student.setRollnum(100);
        student.setDate(null);
        
        Gson gson = new Gson();
        String result = gson.toJson(student);
        System.out.println(result);
    }
}

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

Output

{“id”:1,”name”:”name1″,”rollnum”:100}

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 com.google.gson.Gson;
2  import com.google.gson.GsonBuilder;
3  
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);
11      
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

Output

{“id”:1,”name”:”name1″,”rollnum”:100,”date”:null}


Check these products on Amazon

Leave a Reply