Java Gson enable Serialize null fields
Tags: JSON gson Gson toJson GsonBuilder serializeNulls
In this Java Gson tutorial we learn how to configure Gson to enable serializing null fields during serialization JSON. Via step by step tutorial we will show you how to use the GsonBuilder.serializeNulls() method to configure Gson to serialize null fields.
How to add Gson to the Java project
To use the Gson library in the Gradle build project, add the following dependency into the build.gradle file.
implementation group: 'com.google.code.gson', name: 'gson', version: '2.8.7'
To use the Gson library in the Maven build project, add the following dependency into the pom.xml file.
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.7</version>
</dependency>
Or you can download the Gson jar file from Maven Central at gson-2.8.7.jar
To have more information about the Gson library you can visit the project repository at github.com/google/gson
How to enable Serialize null fields
For example we have the Contact class as below.
Contact.java
public class Contact {
private String firstName;
private String lastName;
private String email;
private int age;
private String address;
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;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
By default Gson omits all fields that are null during serialization. In the following Java example program we learn how to use the GsonBuilder.serializeNulls() method to configure Gson to serialize null fields.
SerializeNullsExample.java
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class SerializeNullsExample {
public static void main(String... args) {
Contact contact = new Contact();
contact.setFirstName("Simple");
contact.setLastName("Solution");
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.serializeNulls().create();
String jsonString = gson.toJson(contact);
System.out.println("Output JSON: ");
System.out.println(jsonString);
}
}
Output JSON:
{"firstName":"Simple","lastName":"Solution","email":null,"age":0,"address":null}
Happy Coding 😊