Gson Explained

Google Gson
Developer:Google
Programming Language:Java
Operating System:Cross-platform
License:Apache License 2.0

Gson, or Google Gson, is an open-source Java 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: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 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 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 DoePhone: 2025550191Age: 0Car 1: Manufacturer: Audi, Model: A4, Capacity: 1.8, Accident: falseCar 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 GitHub repository.

Features

References

[1]

External links

Further reading

  1. More info on com.google.gson package (from javadoc.io)
  2. More info on Gson class (from javadoc.io)

Notes and References

  1. Web site: Jenkov . Jakob . GSON - Gson . 2023-12-28 . tutorials.jenkov.com.