Skip to content
Related Articles

Related Articles

Improve Article

How to Setup GSON For Java Application?

  • Last Updated : 30 Aug, 2021
Geek Week

GSON is Google’s JSON parser. It is used to parse JSON files and generate JSON files. It has multiple APIs which serialize Java objects to JSON and deserializes JSON files to Java objects. To use GSON in your java application, we first need to install it. To do this, we can either add GSON jar dependency in Maven pom.xml file or we can download the jar and add it to our project as shown below:

pom.xml file is as follows:

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.3.1</version>
</dependency>

Let’s understand how Gson serializes and deserializes using various APIs.

Consider XYZ company which maintains Employee information. So we have Employee class with attributes like id, name, department, salary and rating. We create  a Gson instance as follows:

Gson gson = new Gson();

Methods:



  1. Creating an object with all attributes and generate a GSON out of it
  2. Creating a new instance of gson using GsonBuilder

Implementation: 

Method 1: We create an object with all attributes and generate a GSON out of it.

Example

Java




// Java Program to Create an Employee object with all
// Attributes and generate a GSON out of it
 
// Importing input output classes
import com.google.gson.Gson;
import java.io.*;
 
// Main class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Creating an object of Gson class
        Gson gson = new Gson();
        // Creating an object of Employee class
        Employee emp = new Employee();
 
        // Attributes
        emp.setName("John");
        emp.setId("E00101");
        emp.setDepartment("IT");
        emp.setSalary(250000.00);
        emp.setRating(7);
 
        // Generating json from emp object
        String empJson = gson.toJson(emp);
        System.out.println("Emp json is " + empJson);
 
        // Changing one of the attributes of emp object
        emp.setDepartment("Java");
 
        // Generating emp object from emp json
        Employee empGenerated = gson.fromJson(
            gson.toJson(emp), Employee.class);
 
        // Print and display the employee been generated
        System.out.println(
            "Generated employee from json is "
            + empGenerated);
    }
}
 
// Class 2
// Helper class
class Employee {
 
    // Member variables of this class
    private String id;
    private String name;
    private String department;
    private int rating;
    private double salary;
 
    // Member functions of this class
 
    // Method 1
    public String getId() { return id; }
 
    // Method 2
    public void setId(String id) { this.id = id; }
 
    // Method 3
    public String getName() { return name; }
 
    // Method 4
    public void setName(String name) { this.name = name; }
 
    // Method 5
    public String getDepartment() { return department; }
 
    // Method 6
    public void setDepartment(String department)
    {
        this.department = department;
    }
 
    // Method 7
    public int getRating() { return rating; }
 
    // Method 8
    public void setRating(int rating)
    {
        this.rating = rating;
    }
 
    // Method 9
    public double getSalary() { return salary; }
 
    // Method 10
    public void setSalary(double salary)
    {
        this.salary = salary;
    }
 
    // Method  11
    @Override public String toString()
    {
        return "Employee [id=" + id + ", name=" + name
            + ", department=" + department + ", rating="
            + rating + ", salary=" + salary + "]";
    }
}

 
 

Output:

 

Emp json is {"id":"E00101","name":"John","department":"IT","rating":7,"salary":250000.0}
Generated employee from json is Employee [id=E00101, name=John, department=Java, rating=7, salary=250000.0]

Method 2: We can also create a new instance of gson using GsonBuilder.



Syntax:

GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();

Implementation:

Example 1

Java




// Java Program where we will be using GsonBuilder object to
// Pretty Print the gson Contents
 
// Importing I/O classes
import java.io.*;
 
// Class 1
// Main class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        // Creating an object of Employee class
        Employee emp = new Employee();
 
        // Attributes
        emp.setId("F000101");
        emp.setName("Dave");
        emp.setRating(9);
        emp.setDepartment("DB");
        emp.setSalary(150000.00);
 
        // Creating a GSON builder
        GsonBuilder gsonBuilder = new GsonBuilder();
 
        // Creating a GSON from GSON builder
        Gson gson = gsonBuilder.create();
 
        // Creating an employee gson using pretty printing
        String empJson = gsonBuilder.setPrettyPrinting()
                             .create()
                             .toJson(emp);
 
        // Print and display
        System.out.println(
            "Emp json in pretty print format:" + empJson);
 
        // Update rating of emp object
        emp.setRating(8);
 
        Employee updatedEmp = gson.fromJson(
            gson.toJson(emp), Employee.class);
 
        // Print and displaying the updated employee
        System.out.println("Updated employee is : "
                           + updatedEmp);
    }
}
 
// Class 2
// Helper class
class Employee {
 
    // Attributes
    private String id;
    private String name;
    private String department;
    private int rating;
    private double salary;
 
    // Member methods of this class
    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 String getDepartment() { return department; }
 
    public void setDepartment(String department)
    {
        this.department = department;
    }
 
    public int getRating() { return rating; }
 
    public void setRating(int rating)
    {
        this.rating = rating;
    }
 
    public double getSalary() { return salary; }
 
    public void setSalary(double salary)
    {
        this.salary = salary;
    }
 
    @Override public String toString()
    {
        return "Employee [id=" + id + ", name=" + name
            + ", department=" + department + ", rating="
            + rating + ", salary=" + salary + "]";
    }
}

 
 

Output:-
Emp json in pretty print format:{
  "id": "F000101",
  "name": "Dave",
  "department": "DB",
  "rating": 9,
  "salary": 150000.0
}
Updated employee is : Employee [id=F000101, name=Dave, department=DB, rating=8, salary=150000.0]

If we make any field in Employee class as transient, then Gson library will ignore it during serialization and deserialization and set it to its default value. Let’s understand this with an example. 

Example 2

Java




// Java Program to Make Rating Attribute of Employee class
// as Transient
 
// Importing required classes
import java.io.*;
 
// Class 1
// Main class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Creating an object of Gson and user-defined
        // Employee class
        Gson gson = new Gson();
        Employee emp = new Employee();
 
        emp.setName("Jane");
        emp.setId("J01012");
        emp.setDepartment("Devops");
        emp.setSalary(200000.00);
        emp.setRating(7);
 
        // Generating json from emp object
        String empJson = gson.toJson(emp);
        System.out.println("Emp json is " + empJson);
 
        // Changing one of the attributes of emp object
        emp.setDepartment("Java");
 
        // Generate emp object from emp json
        Employee empGenerated = gson.fromJson(
            gson.toJson(emp), Employee.class);
 
        // Print and display the employee generated from
        // json
        System.out.println(
            "Generated employee from json is "
            + empGenerated);
    }
}
 
// Class 2
// Helper class
class Employee {
 
    // Attributes
    private String id;
    private String name;
    private String department;
    private transient int rating;
    private double salary;
 
    // Member methods of this class
 
    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 String getDepartment() { return department; }
 
    public void setDepartment(String department)
    {
        this.department = department;
    }
 
    public int getRating() { return rating; }
 
    public void setRating(int rating)
    {
        this.rating = rating;
    }
 
    public double getSalary() { return salary; }
 
    public void setSalary(double salary)
    {
        this.salary = salary;
    }
 
    @Override public String toString()
    {
        return "Employee [id=" + id + ", name=" + name
            + ", department=" + department + ", rating="
            + rating + ", salary=" + salary + "]";
    }
}

Output:

Emp json is {"id":"J01012","name":"Jane","department":"Devops","salary":200000.0}
Generated employee from json is Employee [id=J01012, name=Jane, department=Java, rating=0, salary=200000.0]

Output explanation:

When the employee object is serialized to json, the rating attribute is not present in the json string as it is marked as transient.  When the json string is deserialized to an employee object, the rating being an int field is set to its default value which is 0. Thus, Gson library ignores transient fields and sets them to their default value based on the data type of the field.

 

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :