- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 }
- Related Articles
- How to serialize and de-serialize generic types using the Gson library in Java?\n
- How to format a date using the Gson library in Java?
- How to serialize a map using the flexjson library in Java?\n
- How to convert Java object to JSON using GSON library?
- How to pretty print JSON using the Gson library in Java?
- How to use @Until annotation using the Gson library in Java?
- Convert a Map to JSON using the Gson library in Java?
- How to write a JSON string to file using the Gson library in Java?
- How to serialize the order of properties using the Jackson library in Java?
- Convert JSON object to Java object using Gson library in Java?\n
- Convert Java object to JSON using the Gson library in Java?\n
- Convert a list of objects to JSON using the Gson library in Java?
- How to exclude a field in Gson during serialization in Java?
- How can we import a gson library in JShell in Java 9?\n
- How to ignore a field of JSON object using the Jackson library in Java?\n

Advertisements