Open In App

How to Install GSON Module in Java?

Last Updated : 02 Mar, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Google GSON is a simple Java-based serialization/deserialization library to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java Object. It is a reliable, fast, and efficient extension to the Java standard library. It’s also highly optimized. Assumes Java is already installed in your local environment.

Setting Up the Path for Linux

The environment variable PATH should be properly set. If you’ve trouble doing this refer to your particular shell documentation. For example: If you use bash as your shell, then you would add the following to the end our your ‘.bashrc’  file:

export PATH=$PATH:/path/to/java

Setting up the Path for Windows

Assumes you have properly installed Java in C:\Program Files\java\jdk-directory

Edit  the ‘ C:\autoexec.bat’   file  and  add  the  following  line  at  the  end:

SET PATH=%PATH%:C:\Program Files\java\jdk\bin

Download GSON Archive

Download the latest GSON archive: https://search.maven.org/artifact/com.google.code.gson/gson/2.8.6/jar
(or)
Maven: 

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

Set CLASSPATH Variable

Manually:

OS

Output

Linux export CLASSPATH=$CLASSPATH:$GSON_HOME/gson-2.8.6.jar:.
Windows

Set the environment variable CLASSPATH to 

%CLASSPATH%;%GSON_HOME%\gson-2.8.6.jar;:;

Mac export CLASSPATH=$CLASSPATH:$GSON_HOME/gson-2.8.6.jar:.

With the help of  IDE: In IntelliJ IDEA: Follow the below steps

Steps: Right Click on Project -> Open Module Settings -> Libraries -> Click +  -> Add GSON Jar  -> Apply and OK

GSON Application

Java




import java.io.*;
import java.util.List;
  
public class Staff {
    private String name;
    private int age;
    private int salary;
    private List<String> skillSet;
  
    public int getSalary() { return salary; }
  
    public void setSalary(int salary)
    {
        this.salary = salary;
    }
  
    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 List<String> getSkillSet() { return skillSet; }
  
    public void setSkillSet(List<String> skillSet)
    {
        this.skillSet = skillSet;
    }
}


Java




import com.google.gson.Gson;
import java.io.*;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
  
public class GSONExample {
    public static void main(String[] args)
    {
        Gson gson = new Gson();
  
        Staff staff = createStaffObj(
            "Anurag", 18, 100,
            Arrays.asList("DevOps", "Machine Learning",
                          "Open Source"));
  
        // Java Object to String
        String json = gson.toJson(staff);
  
        // Java Object to a file
        try (FileWriter writer = new FileWriter(
                 "/home/anurag/gsonexample.txt")) {
            gson.toJson(staff, writer);
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }
  
    public static Staff
    createStaffObj(String name, int age, int salary,
                   List<String> skillSet)
    {
        Staff staff = new Staff();
        staff.setName(name);
        staff.setAge(age);
        staff.setSalary(salary);
        staff.setSkillSet(skillSet);
        return staff;
    }
}


By default, GSON writes JSON in compact mode.

{"name":"Anurag","age":18,"salary":100,"skillSet":["DevOps","Machine Learning","Open Source"]}

After enabling the pretty-print mode:

import com.google.gson.GsonBuilder;

import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

public class GSONExample {
    public static void main(String[] args) {
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        ...
        ...
        ...
        }
 }
{
  "name": "Anurag",
  "age": 18,
  "salary": 100,
  "skillSet": [
    "DevOps",
    "Machine Learning",
    "Open Source"
  ]
}

Converting Java Object to JSON is comparatively easy than parsing with Gson streaming API. By default, JSONWriter writes JSON in compact form but we can set indent for pretty-printing.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads