Gson, or Google Gson, is an open-sourceJava library that serializes Java objects to JSON (and deserializes them back to Java).
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. The latest version, 2.11, was released on May 20, 2024.
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 (no-args) constructor; however, this requirement can be circumvented (see Features).
The following example demonstrates the basic usage of Gson when serializing a sample object:
packagemain;importexample.Car;importexample.Person;importcom.google.gson.Gson;importcom.google.gson.GsonBuilder;publicclassMain{publicstaticvoidmain(String[]args){// Enable pretty printing for demonstration purposes// Can also directly create instance with `new Gson()`; this will produce compact JSONGsongson=newGsonBuilder().setPrettyPrinting().create();Caraudi=newCar("Audi","A4",1.8,false);Carskoda=newCar("Škoda","Octavia",2.0,true);Car[]cars={audi,skoda};PersonjohnDoe=newPerson("John","Doe",2025550191,35,cars);System.out.println(gson.toJson(johnDoe));}}
Calling the code of the above Main class will result in the following JSON output:
moduleGsonExample{requirescom.google.gson;// Open package declared in the example above to allow Gson to use reflection on classes// inside the package (and also access non-public fields)opensexampletocom.google.gson;}
For more extensive examples, see Gson's usage guide on their GitHub repository.
Features
Gson can handle collections, generic types, and nested classes (including inner classes, which cannot be done by default).
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:
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
Excluding fields - rules of what fields are intended to be excluded from deserialization