Gson – Serialize Null Values example shows how to serialize null field values using the Gson library in Java. By default, Gson does not serialize class fields that have null values.
How to serialize null field values in Gson?
The default behavior of Gson skips the fields that have null values in output while serializing. That means, all the class fields having null values are omitted from the JSON when we serialize the object of that class.
In the below given example, when we try to serialize the object of the Student class, the last name field will be omitted from the JSON because it is null.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
package com.javacodeexamples.gsonexamples; import com.google.gson.Gson; public class GsonSerializeNullValues { public static void main(String[] args) { //Student object Student student1 = new Student(1, "John", null); Gson gson = new Gson(); //serialize the student object String jsonData = gson.toJson(student1); System.out.println(jsonData); } } class Student{ private int rollNumber; private String firstName; private String lastName; public Student(int rollNumber, String firstName, String lastName) { this.rollNumber = rollNumber; this.firstName = firstName; this.lastName = lastName; } public int getRollNumber() { return rollNumber; } public void setRollNumber(int rollNumber) { this.rollNumber = rollNumber; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } } |
Output
1 |
{"rollNumber":1,"firstName":"John"} |
As we can see from the output, the lastName field was omitted in the JSON because it was null.
We can easily change this default behavior by creating the Gson object using the GsonBuilder instead of the constructor and calling the serializeNulls
method.
Calling the serializeNulls
method will make Gson include the null fields when we serialize an object to JSON as given below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
//Student object Student student1 = new Student(1, "John", null); /* * Create Gson object using the * GsonBuilder instead of constructor. * * Also, call the serializeNulls method * to allow null fields when serialize. */ Gson gson = new GsonBuilder() .serializeNulls() .create(); //serialize the student object String jsonData = gson.toJson(student1); System.out.println(jsonData); |
Output
1 |
{"rollNumber":1,"firstName":"John","lastName":null} |
As we can see from the output, this time Gson serialized the lastName field even though it was null.
Please let me know your views in the comments section below.