Gson
Java JSON serialization library
Gson, or Google Gson, is an open-source Java library that serializes Java objects to JSON (and deserializes them back to Java).
01History
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.
![Diagram featuring data from 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 }](https://thumb.wikimedia.org/wikipedia/commons/thumb/b/b5/Cars_json.svg/330px-Cars_json.svg.png)
02Usage
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:
package example; 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 example; 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 car : cars) { i++; sb.append("Car ").append(i).append(": ").append(car).append("\n"); } return sb.toString(); } } package main; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import example.Car; import example.Person; public class Main { public static void main(String[] args) { // Enable pretty printing for demonstration purposes // Can also directly create instance with `new Gson()`; this will produce compact JSON Gson gson = new GsonBuilder().setPrettyPrinting().create(); 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)); } }Calling the code of the above Main class will result in the following JSON output:
Since the Person's field age is marked as transient, it is not included in the output.
package main; import com.google.gson.Gson; import example.Person; 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()); } }To deserialize the output produced by the last example, the code above 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: trueThis shows how Gson can be used with the Java Platform Module System for the example above:
module GsonExample { requires com.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) opens example to com.google.gson; }For more extensive examples, see Gson's usage guide on their GitHub repository.
03Features
- 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 the developer can specify:
- Compact/pretty printing (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
- How to convert Java field names
Sources and credits
This article is adapted from the Wikipedia article “Gson”, written by its contributors and licensed under CC BY-SA 4.0. Fathomly has changed the layout, removed citation markers, navigation and maintenance notices, and adjusted punctuation. This adapted version is shared under the same license. For references, see the original article.
Images, from Wikimedia Commons:
- Cars json.svg by Frap, CC0
Fathomly is not affiliated with or endorsed by the Wikimedia Foundation. Spotted a problem? Tell us.