
- Gson - Home
- Gson - Overview
- Gson - Environment Setup
- Gson - First Application
- Gson - Class
- Gson - Object Serialization
- Gson - Data Binding
- Gson - Object Data Binding
- Gson - Tree Model
- Gson - Streaming
- Gson - Serialization Examples
- Gson - Serializing Inner Classes
- Gson - Custom Type Adapters
- Gson - Null Object Support
- Gson - Versioning Support
- Excluding fields from Serialization
GSON - Useful Resources
GSON - Null Support
Gson by default generates optimized Json content ignoring the NULL values. But GsonBuilder provides flags to show NULL values in the Json output using the GsonBuilder.serializeNulls() method.
GsonBuilder builder = new GsonBuilder(); builder.serializeNulls(); Gson gson = builder.create();
Example - Without serializeNulls Call
GsonTester.java
package com.tutorialspoint; import com.google.gson.Gson; public class GsonTester { public static void main(String args[]) { Gson gson = new Gson(); Student student = new Student(); student.setRollNo(1); String jsonString = gson.toJson(student); System.out.println(jsonString); student = gson.fromJson(jsonString, Student.class); System.out.println(student); } } class Student { private int rollNo; private String name; public int getRollNo() { return rollNo; } public void setRollNo(int rollNo) { this.rollNo = rollNo; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String toString() { return "Student[ name = "+name+", roll no: "+rollNo+ "]"; } }
Output
Run the GsonTester and verify the output.
{"rollNo": 1} Student[ name = null, roll no: 1]
Example - With serializeNulls call
GsonTester.java
package com.tutorialspoint; import com.google.gson.Gson; import com.google.gson.GsonBuilder; public class GsonTester { public static void main(String args[]) { GsonBuilder builder = new GsonBuilder(); builder.serializeNulls(); builder.setPrettyPrinting(); Gson gson = builder.create(); Student student = new Student(); student.setRollNo(1); String jsonString = gson.toJson(student); System.out.println(jsonString); student = gson.fromJson(jsonString, Student.class); System.out.println(student); } } class Student { private int rollNo; private String name; public int getRollNo() { return rollNo; } public void setRollNo(int rollNo) { this.rollNo = rollNo; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String toString() { return "Student[ name = "+name+", roll no: "+rollNo+ "]"; } }
Output
Run the GsonTester and verify the output.
{ "rollNo": 1, "name": null } Student[ name = null, roll no: 1]
Advertisements