
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Serialize Null Field Using Gson Library in Java
Gson is a library in the Java that is mainly used for converting Java objects to JSON and vice versa. 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.
Serializing a Null Field Using Gson
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.
In this article, we will learn how to serialize a null field using the Gson library in Java. To use the Gson library, we will need to add it to our project. If you are using Maven, add this to your pom.xml file:
<dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.8.9</version> </dependency>
If you do not use Maven, you can download the jar file from here.
Steps
Following are the steps to serialize a null field using the Gson library:
- Import the Gson library.
- Create a class with fields for name, age, and salary.
- Use the GsonBuilder class to create a Gson object.
- Call the serializeNulls() method on the GsonBuilder instance.
- Set the pretty printing option using the setPrettyPrinting() method.
- Create an instance of the class with null values.
- Convert the object to a JSON string using the toJson() method of the Gson object.
- Print the JSON string.
Example
Following is the code to serialize a null field using the Gson library:
import com.google.gson.*; import com.google.gson.annotations.*; public class NullFieldSerializationExample { public static void main(String args[]) { Gson gson = new GsonBuilder() .serializeNulls() .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
The output of the above code will be:
{ "name": null, "age": 25, "salary": 40000.0 }