Gson - Object Data Binding

Object data binding refers to mapping of JSON to any JAVA Object.

//Create a Gson instance 
Gson gson = new Gson();  

//map Student object to JSON content 
String jsonString = gson.toJson(student);   

//map JSON content to Student object 
Student student1 = gson.fromJson(jsonString, Student.class);


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

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

File -


public class GsonTester { 
   public static void main(String args[]) { 
      Gson gson = new Gson(); 
      Student student = new Student(); 
      String jsonString = gson.toJson(student);          
      Student student1 = gson.fromJson(jsonString, Student.class); 

class Student { 
   private String name; 
   private int age; 
   public Student(){} 
   public String getName() { 
      return name; 
   public void setName(String name) { = name; 
   public int getAge() { 
      return age; 
   public void setAge(int age) { 
      this.age = age; 
   public String toString() { 
      return "Student [ name: "+name+", age: "+ age+ " ]"; 

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.

Student [ name: Mahesh, age: 10 ]