GSON – Quick Guide For Beginners

What is GSON?

Gson, also referred to as Google Gson, is a Java-based library useful for serializing and deserializing Java objects. In other terms, Gson is used to transform Java objects into JSON form. It also converts any JSON string into its respective Java object. 

Gson enables users to customize Java objects and broadly supports Java Generics. It uses two straightforward methods, toJson() for converting the Java object into a JSON string and fromJson() for converting JSON string into Java object. One of the significant goals of Gson is to convert those Java objects into their respective JSON string, which are not modifiable. 

Gson includes serializer and deserializer. Gson serializer enables you to transform the JSON string to its respective Java object. You can serialize several similar Java objects. On the other hand, Gson deserializer transforms the Java object into its separate JSON string. 

Features of Gson:

Here are some most desirable features of Gson.

  • Gson is an open-source Google library, which is a standardized library supported by Java generics. 
  • This Google library also supports complex objects having inheritance hierarchies. It also supports nested classes.
  • During serializing and deserializing Java objects, Gson helps users to create a customizable serializer and deserializer. It will enable users to have their control over the process. Additionally, you can deserialize those Java objects whose code is not available or accessible. 
  • Another Gson characteristic is that it is highly customizable. Users can decide whether they need to print a complex output or human-readable output. 
  • Gson requires less memory and is very quick and fast. 
  • It only depends on the Java Development Kit (JDK) and does not require any other external library. 

How to process JSON?

There are three different ways of processing JSON offered by the Gson library, Streaming API, Tree Model, and Data Binding. Let us discuss each JSON processing form. 

Streaming API

In the streaming API method of processing JSON, all JSON content is read and written as discrete events. The JSON data is read using JsonReader and written using JsonWriter. JsonReader and JsonWriter treat JSON data as a token. This token is referred to as JsonToken. The streaming API method for processing JSON is the most effective and quicker method than the other two. It performs read and write operations quickly and fastly. 

Tree Model

Another JSON processing method is the tree model. In the tree model, JSON content is represented as a tree-like structure. This tree-like structure of JSON data contains JsonObjects nodes. The tree model is the most flexible method for processing JSON. It is the same as that of the XML’s DOS parser. 

Data Binding

The data binding approach for processing JSON uses the property accessor. The property accessor transforms JSON to Plain Old Java Object (POJO) and vice versa. There are data type adapters in the data binding approach, which performs Jsonreads and Jsonwrites. This data binding method is the same as that of the XML’s JAXB parser. 

Environmental Set-up of Gson

If your system does not have a local Java environment set-up, you need to set-up it first. Setting up the Java environment on your system is very straightforward and manageable. Here is a complete guide for you about setting up a local Java environment. Sequentially follow the below-listed steps to successfully set-up a local Java environment. 

  • Firstly, you have to download JavaSE from the website. Make sure you download the JavaSE version compatible with your computer’s operating system
  • Download the JavaSE file and obey the instructions displayed during installation. JavaSE will be installed on your system. 
  • After that, you have set-up the correct path of the environmental variables.

Steps for setting up the Path for Windows 2000/XP

Move the JavaSE file that you downloaded from the above website to the local drive C/Program Files/java/jdk directory. Next, see the below steps to set-up the path for environmental variables. 

  • Go to ‘My Computer,’ and right-click on it. You will notice ‘Properties’ and click on it. 
  • Later, go to the ‘Advanced tab’ and click on the ‘Environmental Variables’ button.
  • Check the Path. Change the Path to the jdk directory, where we have kept the downloaded JavaSE file. If the current path is ‘C:\WINDOWS\SYSTEM32,’ change it to ‘C:\WINDOWS\SYSTEM32;c:\Program Files\java\jdk\bin.’

Steps for setting up the Path for Windows 95 / 98 / ME

After downloading the JavaSE file, move it to the C/Program Files/java/jdk directory. For setting up the path on Windows 95 / 98 / ME, follow the below step:

  • Go to the ‘C:\autoexec.bat’ file. Later, add ‘SET PATH=%PATH%;C:\Program Files\java\jdk\bin’ at the end of the ‘C:\autoexec.bat.’ 

Steps for setting up the Path for Linux, Solaris, FreeBSD, and UNIX systems

For Linux, Solaris, FreeBSD, and UNIX systems, you have to set-up the PATH to the place where all Java binaries are installed. For instance, use bash your shell. Use the following line of code to set-up the path. 

‘.bashrc: export PATH=/path/to/java/java:$PATH’. 

How to set-up a Gson Environment?

Once you have set the Java path, here are the remaining steps for setting up your system’s JSON environment.

  • Firstly, you have to download the Gson archive. Make sure you download the latest version of the Gson archive. Download the Gson archive or Gson jar file from the gson-2.3.1.jar. For Microsoft Windows, Linux, and macOS systems, the JSON archive file name is ‘gson-2.3.1.jar.’ After downloading the gson-2.3.1.jar file, copy it to the C:\>gson folder. 
Operating SystemArchive File Name
Microsoft Windows gson-2.3.1.jar.
Mac OS Xgson-2.3.1.jar.
Linux gson-2.3.1.jar.
  • The next step is to set the path for the GSON_HOME environment variable. You have to fix the GSON_HOME environment variable path to the place where your gson-2.3.1.jar file is located on the system. For different operating systems, the GSON_HOME environment path differs. The below table will guide you in changing the current path of your system to the GSON path. 
Operating SystemResult
Microsoft Windows Change the environmental variable from GSON_HOME to C:\gson.
Mac OS XFollow the below command to change the environmental variable on macOS.exportGSON_HOME = /usr/local/gson
LinuxFollow the below command to change the environmental variable on Linux systems.exportGSON_HOME = /Library/gson
  • After setting the JSON path for the GSON_HOME environment variable, you have to set the environment variable’s CLASSPATH. Fix the CLASSPATH environment variable to the place where your Gson jar file is located.
Operating SystemsResult
Microsoft Windows %CLASSPATH%;%GSON_HOME%\gson-2.3.1.jar;.;
Mac OS Xexport CLASSPATH=$CLASSPATH:$GSON_HOME/gson-2.3.1.jar:.
Linuxexport CLASSPATH=$CLASSPATH:$GSON_HOME/gson-2.3.1.jar:.

Gson Java Example

We have seen how to set-up a local Java environment and Gson environment on your Windows, Linux, and macOS operating systems. Once you set-up everything required to run the Gson code, you are ready to execute any application. You can try one example yourself on your system. 

For trying the below Gson example, you can use any one of the popular Java editors, like Notepad, Netbeans, or Eclipse. Notepad is one of the typical text editors used for writing the Java code. If you have a Windows system, you can use the Notepad text editor for writing the Java code. The other platform is Netbeans. It is an Integrated Development Environment (IDE). You can download Netbeans on your Windows, Linux, Solaris, and macOS systems. Another text editor for Java is Eclipse. Eclipse servers as the text editor for multiple programming languages. You can download Eclipse on Windows, Linux, and macOS systems. 

Before we see the Gson example, remember to create the Java file with the name ‘GsonEmployee,’ which is the Java class name. Later, ensure that your ‘GsonEmployee’ Java file is present in C:\>GSON_WORKSPACE. Save your file in this directory with the .java extension. 

Example:

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

public class GsonEmployee {
  public static void main(String[] args) {
      String empString = "{\"id\":\"RS02\", \"name\":\"John\", \"age\":31, \"position\":\"Manager\" }";
     
      GsonBuilder b1 = new GsonBuilder();
      b1.setPrettyPrinting();
     
      Gson gson = b1.create();
      Employee emp = gson.fromJson(empString, Employee.class);
      System.out.println(emp);   
     
      empString = gson.toJson(emp);
      System.out.println(empString); 
  }
}

class Employee {
  private String id;
  private String name;
  private int age;
  private String position;
  public Employee(){}
  public String getId() {
      return id;
  }
  public void setId(String id) {
      this.id = id;
  }
  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 int getPosition() {
      return position;
  }
  public void setPosition(String position) {
      this.position = position;
  }
  public String toString() {
      return "Employee [ id: "+id+", name: "+name+", age: "+ age+ ", position: "+position+" ]";
  } 
}

Output:

Follow the below-given steps for running the above Gson code. 

  1. Complete the above code using the keyword ‘javac.’
C:\GSON_WORKSPACE>javac GsonEmployee.java
  1. After compiling, run the code using the ‘java’ keyword. 
C:\GSON_WORKSPACE>java GsonEmployee
  1. The result of the above Gson code will be displayed if there are no errors in the code. 
Employee [ id: RS02, name: John, age: 31, position: Manager]
{
  "id" : "RS02",
  "name" : "John",
  "age" : 31,
  "position" : "Manager"
}

Here is a simple guide for you about creating, serializing, and deserializing the Gson object. 

  • Firstly, you have to create a reusable Gson object using the GsonBuilder() function.
GsonBuilder b1 = new GsonBuilder();
b1.setPrettyPrinting();
Gson gson = b1.create();
  • After creating a Gson object, you have to deserialize the JSON string to a Java object. For this purpose, we use the fromJson() function. In this function, you have to pass two parameters, JSON string, and object type. 
Employee emp = gson.fromJson( empString, Employee.class);
  • Later, you need to serialize a Java object to the JSON string using the toJson() function. This function requires only one parameter, an object. 
empString = gson.toJson(emp);

Gson – Object Serialization

Gson object serialization implies reading Java object into a JSON document and then reading the JSON document into a Java object. Let us know how the Gson object serialization takes place with one example. Let us take the same Employee example, as discussed above. We displayed the Employee’s id, name, age, and position. In this example, we will show the same result and look at Gson object serialization. 

Similarly, you have to create a class named GsonEmployee, and place this file in C:\>GSON_WORKSPACE. Remember to save your file name as GsonEmployee.java. 

Example

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException; 

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

public class GsonEmployee {
  public static void main(String args[]) {
 
    GsonEmployee gsonEmp = new GsonEmployee();
      try {
        Employee emp = new Employee();
        emp.setId("RS02");
        emp.setName("John");
        emp.setAge(31);
        emp.setPosition("Manager");
        gsonEmp.writeJSON(emp); 
        Employee emp1 = gsonEmp.readJSON();
        System.out.println(emp1);
      }
      catch(FileNotFoundException e) {
        e.printStackTrace();
      }
      catch(IOException e) {
        e.printStackTrace();
      }
  }
 
  private void writeJSON(Employee emp) throws IOException {
      GsonBuilder b1 = new GsonBuilder();
      Gson gson = b1.create();
      FileWriter fw = new FileWriter("emp.json");  
      fw.write(gson.toJson(emp));  
      fw.close();
  } 
 
  private Employee readJSON() throws FileNotFoundException {
      GsonBuilder b1 = new GsonBuilder();
      Gson gson = b1.create();
      BufferedReader bufferedReader = new BufferedReader(
        new FileReader("emp.json"));  
     
      Employee emp = gson.fromJson(bufferedReader, Employee.class);
      return emp;
  }
}

class Employee {
  private String id;
  private String name;
  private int age;
  private String position;
  public Employee(){}
  public String getId() {
      return id;
  }
  public void setId(String id) {
      this.id = id;
  } 
  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 int getPosition() {
      return position;
  }
  public void setPosition(String Position) {
      this.position = position;
  }
  public String toString() {
      return "Employee [ id: "+id+", name: "+name+", age: "+ age+ ", position: "+position+" ]";
  } 
}

Output:

For executing the above code, you have to follow the above-specified steps. 

  • For compiling the code, use the ‘javac’ keyword.
C:\GSON_WORKSPACE>javac GsonEmployee.java
  • Once compiled, run the code using the ‘java’ keyword. 
C:\GSON_WORKSPACE>java GsonEmployee
  • The result of this code will be the same as the above, displaying the Employee’s name, age, and position. 
Employee [ id: RS02, name: John, age: 31, position: Manager]

Gson Class

We have seen how to serialize the Gson object. In other terms, we have read the Java object into its equivalent JSON string and the JSON string into its respective Java object. Now, we shall move towards the Gson class. 

Gson is the primary and significant class of the Google Gson library. Gson class is responsible for converting Java objects into JSON string and JSON string into respective Java objects. For the Gson class, you need to use the GsonBuilder() function first, and then use toJson(), and fromJson() functions for reading and writing JSON strings. Below is the class declaration syntax for com.google.gson.Gson. 

Syntax:

public final class Gson
extends Object

Gson Constructor

There is a Gson constructor to use in the Java code. It is defined as, Gson(). The Gson() constructor creates the Gson object. As there are no parameters passed to Gson(), it takes default configuration. 

Gson Class Methods

Now we shall move towards Gson class methods. Below are some effective Gson class methods with their description. 

  1. <T> T fromJson(JsonElement json, Class<T> classOfT):

The above Gson class method uses a particular parse tree to deserialize the Json read from it into the specific object type. 

  1. <T> T fromJson(JsonElement json, Type typeOfT):

This Gson class method is also used for the same purpose as the above method. It uses the Json read from the specific parse tree and converts it into its equivalent object type. 

  1. <T> T fromJson(Reader json, Type typeOfT):

The above Gson class method takes Json read from a particular reader and deserializes it into the specific object type. 

  1. <T> T fromJson(JsonReader reader, Type typeOfT):

You can use the above Gson class method for reading the next JSON string or value from a particular reader. After reading, this method transforms the JSON value into the typeOfT object. 

  1. <T> T fromJson(Reader json, Class<T> classOfT):

This Gson class method takes the JSON read from the specific reader and deserializes it into the specified class object. 

  1. <T> TypeAdapter<T> getDelegateAdapter(TypeAdapterFactory skipPast, TypeToken<T> type):

When you require an alternate type adapter for a particular type, you can use the above Gson class method. 

  1. <T> TypeAdapter<T> getAdapter(Class<T> type):

This Gson class method is used for getting the type adapter for the specific type. 

  1. <T> T fromJson(String json, Class<T> classOfT):

When you wish to deserialize any JSON string into a specific class object, you can utilize the above Gson class method.

  1. <T> TypeAdapter<T> getAdapter(TypeToken<T> type):

If you want to get the type adapter for a particular type, this is again one Gson method to use. 

  1. <T> T fromJson(String json, Type typeOfT):

The above Gson class method converts the JSON string into an object of a particular type. 

  1. void toJson(Object src, Appendable writer):

For serializing the specific Java object into its respective JSON representation, the above Gson method is used.

  1. void toJson(JsonElement jsonElement, JsonWriter writer):

The above Gson class method is used for writing JSON to the writer for the jsonElement. 

  1. String toJson(JsonElement jsonElement):

JSON elements are arranged in a tree-like structure. When you desire to represent JSON elements into their equivalent representation, you have to use the above Gson method. 

  1. String toJson(Object src):

The above method is another Gson method used for serializing a particular Java object into its respective JSON string or representation. 

  1. void toJson(JsonElement jsonElement, Appendable writer):

For all JsonELements in a tree, the above Gson class method writes their equivalent JSON. 

  1. void toJson(Object src, Type typeOfSrc, Appendable writer):

This Gson method is used for serializing the specific object into its respective JSON string. It also serializes generic type objects. 

  1. JsonElement toJsonTree(Object src):

The above Gson method converts a particular Java object into its respective JSON value. It represents the JSON value in the JsonElements tree. 

  1. String toJson(Object src, Type typeOfSrc):

Again, the above method is one method in Gson class, which converts the specific Java objects, including all generic types, into their respective JSON values. 

  1. void toJson(Object src, Type typeOfSrc, JsonWriter writer):

This Gson method is used for writing the src of typeOfSrc type into its JSON representation to the writer. 

  1. JsonElement toJsonTree(Object src, Type typeOfSrc):

The above method converts a particular Java object, including all generic types, into the specific JSON representation. It represents the JSON value in the JsonElements tree. 

The Gson class inherits all the above methods from the java.lang.Object class. Let us see one example display employee ID, Name, Age, and Position. Make sure you use the class name the same as that of your file’s name. Consider that we stored our Java file at C:/>GSON_WORKSPACE. In the example mentioned below, the file name is GsonEmployee2.java. 

Example:

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

public class GsonEmployee2 {
  public static void main(String[] args) {
  String empString = "{\"id\":\"RS010\", \"name\":\"Steve\", \"age\":45, \"position\":\"HR\", \"city\": \"Chicago\"}";
     
      GsonBuilder b1 = new GsonBuilder();
      b1.setPrettyPrinting();
     
      Gson gson = b1.create();
      Employee emp = gson.fromJson(empString, Employee.class);
      System.out.println(emp);   
     
      empString = gson.toJson(emp);
      System.out.println(empString); 
  }
} 
class Employee {
  private String id;
  private String name;
  private int age;
  private String position;
  private String city;
  public Employee(){}
  public String getId() {
  return id;
  }
  public void setId(String id) {
      this.id = id;
  }
  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 getPosition() {
      return position;
  }
  public void setPosition(String position) {
      this.position = position;
  }
  public String getCity() {
      return city;
  }
  public void setCity(String city) {
      this.city = city;
  }
  public String toString() {
      return "Employee [ id: "+id+", name: "+name+", age: "+ age+ ", position: "+position+", city: "+city+" ]";
  } 
}

Output:

After writing the Java code and saving it with a name similar to the class name, you need to compile it. Use the below command for compiling.

C:\GSON_WORKSPACE>javac GsonEmployee2.java

The java file, GsonEmployee2.java, gets compiled. 

After compilation, you have run it using the below command.

C:\GSON_WORKSPACE>java GsonEmployee2

The output will be displayed as follows:

Employee [id: RS010, name: Steve, age: 45, position: HR, city: Chicago]
{
"id": "RS101",
"name": "Steve",
"age": 45,
"position: "HR",
"city": "Chicago"
}

Data Binding in Gson

We have seen three different forms of processing JSON provided by Gson. One of the JSON processing forms in Gson is Data Binding. Using the data binding processing form, you can transform JSON to Plain Old Java Object (POJO) and POJO to JSON. Conversion between JSON and POJO takes place using the property accessor or annotations. The property accessor annotations are of two different types, Primitives Data Binding and Objects Data Binding. 

Primitives Data Binding: This property accessor or annotation transforms JSON to the object of various Java data types, like Maps, Strings, Booleans, Lists, and Null. It also converts all these mentioned object data types into JSON. 

Objects Data Binding: The objects data binding converts any JSON value to JAVA type and vice-versa. 

The data binding approach of processing JSON is similar to the XML’ JAXB parse. Gson can read and write JSON values in any of the above two data binding types. Let us study each data binding type in detail below. 

Primitives Data Binding

Primitives Data Binding approach for processing JSON converts the JSON value into any of the Java data types. In the data binding approach, Gson offers several built-in adapters. These adapters are used for serializing and deserializing primitive data types. Let us understand the primitives data binding method of Gson for processing JSON using one example. 

Below is an example showing the conversion between JSON and Java primitive data types. You have to remember that your file name should be the same as that of the class name. Save your file in the C:\>GSON_WORKSPACE. In the below example, the filename is GsonEmployee3.java. 

Example:

import com.google.gson.Gson; 
public class GsonEmployee3 {
public static void main(String args[])
{
Gson gson = new Gson(); 
String emp_name = "Robert Willaims";
long emp_id = 1445;
boolean is_manager = true;
double salary_in_dollars = 40,000; 
String emp_city = "California";
      //Serialization
System.out.println("{");
System.out.println("Name: " + gson.toJson(emp_name) +",");
System.out.println("ID: " + gson.toJson(emp_id) +",");
System.out.println("is_manager: " + gson.toJson(is_manager) +",");
System.out.println("Salary:" + gson.toJson(salary_in_dollars)+",");
System.out.println("City: " + gson.toJson(emp_city));
System.out.println("}"); 
      //De-serialization
emp_name = gson.fromJson("\"Robert Williams\"", String.class);
emp_id = gson.fromJson("1445", Long.class);
is_manager = gson.fromJson("true", Boolean.class);
salary_in_dollars = gson.fromJson("40,000", Double.class); 
emp_city = gson.fromJson("California", String.class);
  System.out.println("Name: " + emp_name);
  System.out.println("ID: " + emp_id);
  System.out.println("is_manager: " +is_manager);
  System.out.println("Salary:" + salary_in_dollars);
  System.out.println("City:" + emp_city);
  }
}

Output:

Firstly, you need to compile the above code using the below command.

C:\>GSON_WORKSPACE>javac GsonEmployee3.java

After compiling, you have to run the code using the below command. 

C:\>GSON_WORKSPACE>java GsonEmployee3

The following output will be displayed.

{
Name: "Robert Williams",
ID: 1445,
is_manager: true,
Salary: 40,000,
City: "California"
}

Name: Robert Williams
ID: 1445
is_manager: true
Salary: 40,000
City: California

Here, you can clearly observe the dissimilarity between the output generated after serializing and deserializing using the primitives data binding approach. 

Objects Data Binding

Now, we shall move towards the Objects Data Binding approach of Gson for processing JSON. This approach maps the JSON value to any JAVA type and any Java object to its respective JSON representation. The Objects Data Binding process is explained below:

  1. Firstly, you need to create a Gson instance using the Gson() method.
Gson gson = new Gson();
  1. Now, convert the Java object to the JSON value. Consider the Java object as emp for the class, Employee. 
String jsStr = gson.toJson(emp);
  1. Lastly, convert the JSON value or string into its respective Java object. Consider the class Employee and take an object as emp1. 
Employee emp1 = gson.fromJson(jsStr, Employee.class);

Using these above steps, we will execute one straightforward example of the objects data binding approach. We will use the class name as GsonEmployee4. Hence, the filename should be saved as GsonEmployee4.java. In this example, we will display an employee’s information containing name, id, position, age, and city. 

Example:

import com.google.gson.Gson; 
public class GsonEmployee4 {
  public static void main(String args[])
{
      Gson gson = new Gson();
      Employee emp = new Employee();
      emp.setId("RS014");
      emp.setName("Oliver");
      emp.setAge(50);
      emp.setPosition("HR");
      emp.setCity("Washington DC");
     
      String jsStr = gson.toJson(emp);         
      System.out.println(jsStr);
     
      Employee emp1 = gson.fromJson(jsStr, Employee.class);
      System.out.println(emp1);
  }  
}

class Employee {
  private String id;
  private String name;
  private int age;
  private String position;
  private String city;
  public Employee(){}
    public String getId() {
      return id;
  }
  public void setId(String id) {
      this.id = id;
  }
  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 getPosition() {
      return position;
  }
  public void setPosition(String position) {
      this.position = position;
  }
public String getCity() {
      return city;
  }
  public void setCity(String city) {
      this.city = city;
  }
  public String toString() {
      return "Student [ id: "+id+", name: "+name+", age: "+ age+ ", position: "+position+", city: "+city+" ]";
  } 
}

Output:

Now, you have to compile your code. Follow the below command for compiling. 

C:\>GSON_WORKSPACE>javac GsonEmployee4.java

Run your code using the command,

C:\>GSON_WORKSPACE>java GsonEmployee4

You will get the following output:

{"id": "RS014", "name": "Oliver", "age": 50, "position", "HR", "city": "Washington DC"}
Employee [ id: RS014, name: Oliver, age: 50, position: HR, city: Washington DC ]

Here, we have observed the Data Binding approach of Gson for processing JSON with examples. Let us now watch another JSON processing approach. 

Streaming API in Gson

The Streaming API is another Gson’s form for processing JSON. In the Streaming API approach, the JSON value is read and written as a token. This approach considers each JSON value as a discrete event. Here, JsonReader reads the JSON data, and JsonWriter writes the Json data as a token. Hence, it is known as JsonToken. 

Streaming API is very well-known for monitoring every JSON data carefully. In this article, we shall see reading the JSON data using the Streaming API method. The reading process for JSON data takes place as follows:

  • As we are focusing on reading the JSON data, we will use the JsonReader() function. Firstly, you need to generate an object of the JsonReader() function and pass this object to the JSON text. 
JsonReader jsread = new JsonReader( new StringReader(jsStr));

Here, ‘jsread’ is the object of the JsonReader() function. 

  • After creating an object, begin to read the JSON text with that object and get the token. 
jsread.beginObject();
JsonToken jstoken = jsread.peek();
  • Lastly, you have to check the token type that you get after reading the JSON text. 
if(jstoken.equals(JsonToken.NAME))
{
fieldname = jsread.nextName();
}

We shall see one example of JsonReader. Take the class name as EmployeeRead. Make sure to save the file name as EmployeeRead.java in the C:\<GSON_WORKSPACE. 

Example:

import java.io.IOException;
import java.io.StringReader;  
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;  
public class EmployeeRead {
  public static void main(String args[]) {
    String jsStr = "{\"id\":\"RS02\",\"name\":\"John Doe\", \"age\": 45,\"is_manager\":true,\"position\": \"Manager\", \"city\": \"Chicago\"}"; 
      JsonReader jsread = new JsonReader(new StringReader(jsStr));    
      try {
        handleJsonObject(jsread);
      }
      catch (IOException e) {
        e.printStackTrace();
      }
  }
private static void handleJsonObject(JsonReader jsread) throws IOException
{
      jsread.beginObject();
      String fieldname = null;
          while (jsread.hasNext())
{
        JsonToken jstoken = jsread.peek();          
            if (jstoken.equals(JsonToken.NAME)) {  
              fieldname = jsread.nextName();
            }
              if("id".equals(fieldname)) {
              jstoken = jsread.peek();
              System.out.println("ID:" + jsread.nextString());           
            }       
              if ("name".equals(fieldname)) {    
              jstoken = jsread.peek();
              System.out.println("Name: "+jsread.nextString());           
            }
           
            if("age".equals(fieldname)) {
            jstoken = jsread.peek();
            System.out.println("Age:" + jsread.nextInt());       
            }
              if("is_manager".equals(fieldname)) {
                jstoken = jsread.peek();
              System.out.println("is_manager:" + jsread.nextBoolean());           
            }       
            if("position".equals(fieldname)) {
              jstoken = jsread.peek();
              System.out.println("Position:" + jsread.nextString());           
            }       
            if("city".equals(fieldname)) {
                jstoken = jsread.peek();
              System.out.println("City:" + jsread.nextString());           
            }            
        }
      }
  } 

Output:

For compiling the above code, type the command as follows,

C:\>GSON_WORKSPACE>javac EmployeeRead.java

After compiling, run the program using the below line of code,

C:\>GSON_WORKSPACE>java EmployeeRead

The output will be as follows:

ID: RS02
Name: John Doe
Age: 45
Is_manager: true
Position: Manager
City: Chicago

This was all about the Streaming API approach for processing JSON. Now, let us move towards the final form, Tree Model. 

Tree Model in Gson

The last approach in processing JSON offered by Gson is the Tree Model. As its name suggests, it represents the JSON document in a tree-like structure. This tree-like structure involves JsonObject nodes. The Tree Model is similar to the XML’s DOM parser. Let us now see how to create a tree and how to traverse the tree. 

How to create a tree from a JSON document?

For creating the tree from the JSON document, we will use the JsonParser() method. The JsonParser() method has a pointer with it, which reads the JSON document and points to the tree’s root. Using a single root node, we can traverse through an entire tree. Here is a small code that will help you in creating a tree from the JSON data. 

Follow the below steps for creating a tree from JSON data:

  • The JsonParser() method is used for creating a tree. The first step is to make the JsonParser() method’s instance or object. 
JsonParser jsparser = new JsonParser();

Here, ‘jsparser’ is the object of the JsonParser() method. 

  • The next step is to specify the string or JSON data you want to depict in a tree-like structure. 
String jsStr = "{\"id\": \"RS02\", \"name\": \"John"\, \"age\": 45, \"position\": \"Manager\"}";
  • The last step is to create a tree from the above-specified data. 
JsonElement rootNode = jsparser. parse(jsStr);

How to traverse a tree?

We have seen how to create a tree from JSON data. Now, we shall observe how to traverse the designed tree from the JSON document. For traversing the tree, you have to see every node’s path from that particular node to the root node. Here is a small code for you guiding about traversing a tree. 

JsonObject jsobj = rootNode. getAsJsonObject();
JsonElement idNode = details.get("id");
System.out.println("ID: " +idNode.getAsString());
JsonElement nameNode = details.get("name");
System.out.println("Name: " + nameNode.getAsString()); 

This was a more straightforward example of traversing the tree. Now, we shall have a single instance of creating and traversing the tree from the jSON data. We will create a class name as GsonTree. Therefore, make sure to save the file with the name, GsonTree.java, in the C:\>Gson_WORKSPACE. 

Example:

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonPrimitive;  
public class GsonTree {
  public static void main(String args[]) {
        String jsStr =
"{\"id\":\"RS014\", \"name\":\"Robert Williams\", \"age\":50,\"position\":\"HR\",\"city\": \"Washington DC\"}";
      JsonParser jsparser = new JsonParser();  
      JsonElement rootNode = jsparser.parse(jsStr);  
            if (rootNode.isJsonObject()) {
        JsonObject jsobj = rootNode.getAsJsonObject(); 
        JsonElement idNode = jsobj.get("name");
        System.out.println("ID: " +idNode.getAsString()); 
       
        JsonElement nameNode = jsobj.get("name");
        System.out.println("Name: " + nameNode.getAsString()); 
       
        JsonElement ageNode = jsobj.get("age");
        System.out.println("Age: " + (ageNode.getAsInt())); 
       
        JsonElement positionNode = jsobj.get("position");
        System.out.println("Position: " + (positionNode.getAsString()));

      JsonElement cityNode = jsobj.get("city");
      System.out.println("City: " + (cityNode.getAsString()));
      }
  }  
}

Output:

For compiling the above program, use the below command, 

C:\>GSON_WORKSPACE>javac GsonTree.java

After compiling, you need to run using the below code, 

C:\>GSON_WORKSPACE>java GsonTree

The output will be displayed as follows:

ID: RS014
Name: Robert Williams
Age: 50
Position: HR
City: Washington DC

We have seen all three JSON processing forms offered by Gson with respective examples. Let us now execute some serialization and deserialization examples in Gson. 

Serialization and Deserialization Examples in Gson

This section will provide you with some easy and straightforward serialization and deserialization examples in Gson. We will look at Array, Collections, and Generic Types examples. 

Array Example in Gson

We will present here a small code for a better understanding of array serialization and deserialization. 

String[] color = {"Black", "Red", Orange"};
//Serialization
System.out.println("Color:" + gson.toJson(color));     
//De-serialization
color = gson.fromJson("[100,90,85]", String[].class);
System.out.println("Color:" + Arrays.toString(color)); 

Now, we shall execute a complete code, which will make you understand array serialization and deserialization. We will create a class GsonColor. Ensure to save your Java file, named GsonColor.java, in the C:\>GSON_WORKSPACE. 

Example:

import java.util.Arrays;
import com.google.gson.Gson; 

public class GsonColor {
  public static void main(String args[]) {
 
      Gson gson = new Gson();
      int[] colour_code = {2001, 3004, 5006, 6789};
      String[] color = {"Blue","Yellow","Red", "White"};
     
      //Serialization
      System.out.print("{");
      System.out.print("Color Code:" + gson.toJson(color_code) + ",");      
      System.out.print("Colors:" + gson.toJson(color));      
      System.out.println("}"); 
     
      //De-serialization
      color_code = gson.fromJson("[2001, 3004, 5006, 6789]", int[].class);
      color = gson.fromJson("[\"Blue\",\"Yellow\",\"Red\", \"White\"]", String[].class);
      System.out.println("Color Code:" + Arrays.toString(color_code));
      System.out.println("Colors:" + Arrays.toString(color));    
  }     
} 

Output:

For compiling the above code, type the below command, 

C:\>GSON_WORKSPACE>javac GsonColor.java

Run the above code using the command as follows,

C:\>GSON_WORKSPACE>java GsonColor

The output will be displayed as:

{color_code: [2001, 3004, 5006, 6789], color: ["Blue", "Yellow", "Red",  "White"]}
color_code: [2001, 3004, 5006, 6789]
color: [Blue, Yellow, Red, White]

Generics example in Gson

In Gson, there is a Java reflection API. This API is useful in identifying the object type to which the JSON string or value is mapped. When you use generics in Gson, the JSON value represented in its respective object type is not available in serialization. Therefore, to overcome this issue in Gson generics, there is a class, com.google.gson.reflect.TypeToken. This class’s primary function is to hold the generic object. 

We will have one generics type example below. Let us create a class, GsonGenerics. Make sure to save the Java program file in C:\>GSON_WORKSPACE with the name GsonGenerics.java

Example

package net.javaguides.gson;
import java.lang.reflect.Type;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

public class GsonGenerics {
    public static void main(String[] args) {
        Gson gson = new GsonBuilder().setPrettyPrinting().create();

        Box < Employee > type2 = new Box < > ();
        Employee emp = new Employee();
        emp.setId(1433);
        emp.setFirstName("John");
        emp.setPosition("Manager");
        emp.setCity("Chicago");
        emp.setAge(45);
        type2.set(emp);

        // Serialization of generic User type to json

        Type fooType2 = new TypeToken < Box < Employee >> () {}.getType();
        String empJson = gson.toJson(type2, fooType2);
        System.out.println(empJson);

        //  De-serialization of generic User type to json
        Box < Employee > box = gson.fromJson(empJson, fooType2);
        System.out.println(box.get().toString());
    }
}

class Box < T > {
    private T t;

    public void set(T t) {
        this.t = t;
    }

    public T get() {
        return t;
    }
}

Output

Compile the above code using the command

C:\>GSON_WORKSPACE>javac GsonGenerics.java

Run the code using the below command

C:\>GSON_WORKSPACE>java GsonGenerics

The above program when executed will generate the following output.

{
  "t": {
    "id": 1433,
    "firstName": "John",
    "position": "Manager",
    "city": "Chicago"
    "age": 45,
  }
}
Employee [id=1433, firstName=John, position=Manager, city=Chicago age=45]

Collections Example in Gson

The collections example in Gson includes the ArrayList() method. Here is a small code lock for you to understand the serialization and deserialization collections example in Gson.

List city = new ArrayList();
//Serialization
System.out.println("Cities:" + gson.toJson(city));      
//De-serialization
//get the type of the collection.
Type listCity = new TypeToken<list>(){}.getType();
//pass the type of collection
city = gson.fromJson("["Chicago", "Washington DC", "New York", "Los Angeles" ]", listCity);
System.out.println("Cities:" +city);</list>

This was the small code. Now let us look at some bigger lines of code representing the serialization and deserialization of collections in Gson. Create a class GsonCollection and save the Java program file with the name, GsonCollection.java. Save the file in C:\>GSON_WORKSPACE. 

Example

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection; 
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken; 
public class GsonCollection {
  public static void main(String args[]) {
        Gson gson = new Gson();
      Collection<String> city = new ArrayList<String>(); 
      city.add("Chicago");
      city.add("Washington DC");
      city.add("New York"); 
      city.add("Los Angeles");
     
      //Serialization
      System.out.print("{");
      System.out.print("Cities:" + gson.toJson(city));            
      System.out.println("}"); 
     
      //De-serialization
      Type listCity = new TypeToken<Collection<String>>(){}.getType();
      city = gson.fromJson("["Chicago", "Washington DC", "New York", "Los Angeles" ]", listCity);
      System.out.println("Cities:" +city);    
  }     
}

Output

Compile the file using the below command, 

C:\>GSON_WORKSPACE>javac GsonCollection.java

Run the above file by typing then the following command on the command prompt,

C:\>GSON_WORKSPACE>java GsonCollection

The following is the result of the above collections program in Gson.

{cities: ["Chicago", "Washington DC", "New York", "Los Angeles"]}
cities: Chicago, Washington DC, New York, Los Angeles

Conclusion

Gson is a toolkit, which enables you to convert JSON string or value into the respective Java object and the Java object into its equivalent JSON string or value. Gson offers three different processing approaches for JSON. 

  • Data Binding transforms JSON value to POJO and POJO to the respective JSON value. 
  • The Streaming API approach uses JsonReader and JsonWriter for reading and writing JSON data as a token. 
  • The tree model method represents the JSON document into a tree-like structure.

We have seen how to set-up the environment variable for Gson. After setting up the Gson environment variable, you run the Gson code. Next, you can see an example of object serialization. In object serialization, the JSON document is read into the Java object, and the Java object is read into its respective JSON document. 

Next, we have seen the simple Gson program and Gson class methods. Each JSON processing approach, Data Binding, Tree Model, and Streaming API are explained with one example each. Later, we have covered serialization and deserialization examples in Gson. We executed an array example, generic type example, and collections example. 

Recommended Articles