This article does not cite any sources. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed.Find sources: "Gson" – news · newspapers · books · scholar · JSTOR (August 2020) (Learn how and when to remove this template message)
Google Gson
Developer(s)Google
Initial releaseMay 22, 2008; 13 years ago (2008-05-22)
Stable release
2.9.0 / 12 February 2022; 2 months ago (2022-02-12)
Repository
Written inJava
Operating systemCross-platform
LicenseApache License 2.0
Websitegithub.com/google/gson

Gson (also known as Google Gson) is an open-source Java library to serialize and deserialize Java objects to (and from) JSON.

History

The Gson library was originally developed for internal purposes of Google, and Version 1.0 was later released on May 22, 2008 under the terms of Apache License 2.0. The latest version, 2.9.0, was released on Feb 12, 2022.

Version history

Usage

Gson uses reflection, so it does not require classes being serialized or de-serialized to be modified. By default, it just needs the class to have defined default no-args constructor (which can be worked around, see Features).

The following example demonstrates the most basic usage of Gson when serializing a sample object:

module GsonExample {
    requires gson;
    requires java.sql; // Required by gson
    exports Person;
    exports Car;
}
package Car;

public class Car {
    public String manufacturer;
    public String model;
    public double capacity;
    public boolean accident;

    public Car() {
    }

    public Car(String manufacturer, String model, double capacity, boolean accident) {
        this.manufacturer = manufacturer;
        this.model = model;
        this.capacity = capacity;
        this.accident = accident;
    }

    @Override
    public String toString() {
        return ("Manufacturer: " + manufacturer + ", " + "Model: " + model + ", " + "Capacity: " + capacity + ", " + "Accident: " + accident);
    }
}
package Person;

import Car.Car;

public class Person {
    public String name;
    public String surname;
    public Car[] cars;
    public int phone;
    public transient int age;

    public Person() {
    }

    public Person(String name, String surname, int phone, int age, Car[] cars) {
        this.name = name;
        this.surname = surname;
        this.cars = cars;
        this.phone = phone;
        this.age = age;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("Name: ").append(name).append(" ").append(surname).append("\n");
        sb.append("Phone: ").append(phone).append("\n");
        sb.append("Age: ").append(age).append("\n");
        int i = 0;
        for (Car item : cars) {
            i++;
            sb.append("Car ").append(i).append(": ").append(item).append("\n");
        }
        return sb.toString();
    }
}

After calling

package Main;

import Car.Car;
import Person.Person;
import com.google.gson.Gson;

public class Main {
    public static void main(String[] args) {
        Gson gson = new Gson();
        Car audi = new Car("Audi", "A4", 1.8, false);
        Car skoda = new Car("Škoda", "Octavia", 2.0, true);
        Car[] cars = {audi, skoda};
        Person johnDoe = new Person("John", "Doe", 2025550191, 35, cars);
        System.out.println(gson.toJson(johnDoe));
    }
}

you will get this output:

{
   "name":"John",
   "surname":"Doe",
   "cars":[
      {
         "manufacturer":"Audi",
         "model":"A4",
         "capacity":1.8,
         "accident":false
      },
      {
         "manufacturer":"Škoda",
         "model":"Octavia",
         "capacity":2.0,
         "accident":true
      }
   ],
   "phone":2025550191
}

Since the Person's field "age" is marked as transient, it is not included in the output.

To deserialize output produced by last example, you can execute the following code:

package Main;

import Person.Person;
import com.google.gson.Gson;

public class Main {
    public static void main(String[] args) {
        Gson gson = new Gson();
        String json = "{\"name\":\"John\",\"surname\":\"Doe\",\"cars\":[{\"manufacturer\":\"Audi\",\"model\":\"A4\"," +
                "\"capacity\":1.8,\"accident\":false},{\"manufacturer\":\"Škoda\",\"model\":\"Octavia\",\"capacity\"" +
                ":2.0,\"accident\":true}],\"phone\":2025550191}";
        Person johnDoe = gson.fromJson(json, Person.class);
        System.out.println(johnDoe.toString());
    }
}

And the following output will be generated:

Name: John Doe
Phone: 2025550191
Age: 0
Car 1: Manufacturer: Audi, Model: A4, Capacity: 1.8, Accident: false
Car 2: Manufacturer: Škoda, Model: Octavia, Capacity: 2.0, Accident: true

The following example demonstrates how to pretty print a Json using Gson library.

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import lombok.SneakyThrows;

public class PrettyPrintExample {
  //SneakyThrows annotation will internally declare all checked exceptions.
  @SneakyThrows
  public static void main(String[] args) {
    List<String> cars= Arrays.asList("Fiat","BMW","Lamborghini");
    //Create new GSON object
    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    String prettyJson=gson.toJson(cars);
    System.out.println("pretty "+prettyJson);
  }
}

And the following output will be generated:

pretty [
  "Fiat",
  "BMW",
  "Lamborghini"
]

Features

  • Compact/pretty printing (whether you want compact or readable output)
  • How to handle null object fields - by default they are not present in the output
  • Rules of what fields are intended to be excluded from (de)serialization
  • How to convert Java field names