
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
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 }
Advertisements