How to serialize a null field using Gson library in Java?


By default, the Gson object does not serialize the 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 via the GsonBuilder class. We need to call the serializeNulls() method on the GsonBuilder instance before creating the Gson object. Once serializeNulls() has been called the Gson instance created by the GsonBuilder can include null fields in the serialized JSON.

Syntax

public GsonBuilder serializeNulls()

Example

import com.google.gson.*;
import com.google.gson.annotations.*;
public class NullFieldTest {
   public static void main(String args[]) {
      GsonBuilder builder = new GsonBuilder();
      builder.serializeNulls();
      Gson gson = builder.setPrettyPrinting().create();
      Employee emp = new Employee(null, 25, 40000.00);
      String jsonEmp = gson.toJson(emp);
      System.out.println(jsonEmp);
   }
}
// Employee class
class Employee {
   @Since(1.0)
   public String name;
   @Since(1.0)
   public int age;
   @Since(2.0)
   public double salary;
   public Employee(String name, int age, double salary) {
      this.name = name;
      this.age = age;
      this.salary = salary;
   }
}

Output

{
   "name": null,
   "age": 25,
   "salary": 40000.0
}

Updated on: 04-Jul-2020

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements