Gson - Data Binding


Advertisements

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

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.

File − GsonTester.java

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

Verify the result

Compile the classes using javac compiler as follows −

C:\GSON_WORKSPACE>javac GsonTester.java

Now run the GsonTester to see the result −

C:\GSON_WORKSPACE>java GsonTester

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