Gson


Gson, or Google Gson, is an open-source Java library that serializes Java objects to JSON.

History

The Gson library was originally developed for internal purposes at Google, with Version 1.0 released on May 22, 2008, under the terms of the Apache License 2.0.

Usage

Gson utilizes reflection, meaning that classes do not have to be modified to be serialized or deserialized. By default, a class only needs a defined default constructor; however, this requirement can be circumvented.
The following example demonstrates the basic usage of Gson when serializing a sample object:

package example;
public class Car


package example;
public class Person


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

Calling the code of the above class will result in the following JSON output:
Since the Person's field is marked as transient, it is not included in the output.

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

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

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

This shows how Gson can be used with the Java Platform Module System for the example above:

module GsonExample

For more extensive examples, see Gson's usage guide on their .

Features

  • Gson can handle collections, generic types, and nested classes.
  • When deserializing, Gson navigates the type tree of the object being deserialized, which means that it ignores extra fields present in the JSON input.
  • The user can:
  • * write a custom serializer and/or deserializer so that they can control the whole process, and even deserialize instances of classes for which the source code is inaccessible.
  • * write an InstanceCreator, which allows them to deserialize instances of classes without a defined no-args constructor.
  • Gson is highly customizable, as you can specify: