Gson


Gson is an open-source Java library to serialize and deserialize Java objects to 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.8.6, was released on October 4, 2019.

Version history

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.
The following example demonstrates the most basic usage of Gson when serializing a sample object:

module GsonExample


package Car;
public class Car


package Person;
import Car.Car;
public class Person

After calling

package Main;
import Car.Car;
import Person.Person;
import com.google.gson.Gson;
public class Main

you will get this output:


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

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

And the following output will be generated:

pretty
"Fiat",
"BMW",
"Lamborghini"

Features