Gson - Data Binding


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.


Let's see primitive data binding in action. Here we'll map JAVA basic types directly to JSON and vice versa.

Create a Java class file named GsonTester in C:\>Gson_WORKSPACE.


import java.util.Arrays; 

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};  
      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)); 
      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)); 

Verify the result

Compile the classes using javac compiler as follows −


Now run the GsonTester to see the result −

C:\GSON_WORKSPACE>java GsonTester

Verify the output.

name: "Mahesh Kumar", 
rollNo: 1, 
verified: false, 
name: Mahesh Kumar 
rollNo: 1 
verified: false 
marks:[100, 90, 85]