
- 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 - Data Binding
Overview
Data Binding API is used to convert JSON to and from POJO (Plain Old Java Object) using property accessor or using annotations. It is of two types.
Primitives Data Binding − Converts JSON to and from Java Maps, Lists, Strings, Numbers, Booleans, and NULL objects.
Objects Data Binding − Converts JSON to and from any JAVA type.
Gson reads/writes JSON for both types of data bindings. Data Binding is analogous to JAXB parser for XML.
Primitives Data Binding
Primitives data binding refers to mapping of JSON to JAVA Core data types and inbuilt collections. Gson provides various inbuilt adapters which can be used to serialize/deserialize primitive data types.
Example - Primitive Data Binding
Let's see primitive data binding in action. Here we'll map JAVA basic types directly to JSON and vice versa.
GsonTester.java
package com.tutorialspoint; import java.util.Arrays; import com.google.gson.Gson; public class GsonTester { public static void main(String args[]) { Gson gson = new Gson(); String name = "Mahesh Kumar"; long rollNo = 1; boolean verified = false; int[] marks = {100,90,85}; //Serialization System.out.println("{"); System.out.println("name: " + gson.toJson(name) +","); System.out.println("rollNo: " + gson.toJson(rollNo) +","); System.out.println("verified: " + gson.toJson(verified) +","); System.out.println("marks:" + gson.toJson(marks)); System.out.println("}"); //De-serialization name = gson.fromJson("\"Mahesh Kumar\"", String.class); rollNo = gson.fromJson("1", Long.class); verified = gson.fromJson("false", Boolean.class); marks = gson.fromJson("[100,90,85]", int[].class); System.out.println("name: " + name); System.out.println("rollNo: " + rollNo); System.out.println("verified: " +verified); System.out.println("marks:" + Arrays.toString(marks)); } }
Output
Run the GsonTester and verify the output.
{ name: "Mahesh Kumar", rollNo: 1, verified: false, marks:[100,90,85] } name: Mahesh Kumar rollNo: 1 verified: false marks:[100, 90, 85]