Gson - First Application


Advertisements

Before going into the details of the Google Gson library, let's see an application in action. In this example, we've created a Student class. We'll create a JSON string with student details and deserialize it to student object and then serialize it to an JSON String.

Example

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

File − GsonTester.java

import com.google.gson.Gson; 
import com.google.gson.GsonBuilder;  

public class GsonTester { 
   public static void main(String[] args) { 
      String jsonString = "{\"name\":\"Mahesh\", \"age\":21}"; 
      
      GsonBuilder builder = new GsonBuilder(); 
      builder.setPrettyPrinting(); 
      
      Gson gson = builder.create(); 
      Student student = gson.fromJson(jsonString, Student.class); 
      System.out.println(student);    
      
      jsonString = gson.toJson(student); 
      System.out.println(jsonString);  
   } 
} 

class Student { 
   private String name; 
   private int age; 
   public Student(){} 
   
   public String getName() { 
      return name; 
   }
   
   public void setName(String name) { 
      this.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 −

C:\GSON_WORKSPACE>javac GsonTester.java

Now run the GsonTester to see the result −

C:\GSON_WORKSPACE>java GsonTester

Verify the output.

Student [ name: Mahesh, age: 21 ] 
{ 
   "name" : "Mahesh", 
   "age" : 21 
}

Steps to Remember

Following are the important steps to be considered here.

Step 1 − Create Gson object using GsonBuilder

Create a Gson object. It is a reusable object.

GsonBuilder builder = new GsonBuilder(); 
builder.setPrettyPrinting(); 
Gson gson = builder.create();

Step 2 − Deserialize JSON to Object

Use fromJson() method to get the Object from the JSON. Pass Json string / source of Json string and object type as parameter.

//Object to JSON Conversion 
Student student = gson.fromJson(jsonString, Student.class);

Step 3 − Serialize Object to JSON

Use toJson() method to get the JSON string representation of an object.

//Object to JSON Conversion   
jsonString = gson.toJson(student); 
Advertisements