Gson

Last updated
Google Gson
Developer(s) Google
Initial releaseMay 22, 2008;16 years ago (2008-05-22)
Stable release
2.11.0 [1]   OOjs UI icon edit-ltr-progressive.svg / 20 May 2024;39 days ago (20 May 2024)
Repository
Written in Java
Operating system Cross-platform
License Apache License 2.0
Website github.com/google/gson

Gson, or Google Gson, is an open-source Java library that serializes Java objects to JSON (and deserializes them back to Java).

Contents

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.10.1, was released on January 6, 2023.

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:

packageexample;publicclassCar{publicStringmanufacturer;publicStringmodel;publicdoublecapacity;publicbooleanaccident;publicCar(){}publicCar(Stringmanufacturer,Stringmodel,doublecapacity,booleanaccident){this.manufacturer=manufacturer;this.model=model;this.capacity=capacity;this.accident=accident;}@OverridepublicStringtoString(){return("Manufacturer: "+manufacturer+", "+"Model: "+model+", "+"Capacity: "+capacity+", "+"Accident: "+accident);}}
packageexample;publicclassPerson{publicStringname;publicStringsurname;publicCar[]cars;publicintphone;publictransientintage;publicPerson(){}publicPerson(Stringname,Stringsurname,intphone,intage,Car[]cars){this.name=name;this.surname=surname;this.cars=cars;this.phone=phone;this.age=age;}@OverridepublicStringtoString(){StringBuildersb=newStringBuilder();sb.append("Name: ").append(name).append(" ").append(surname).append("\n");sb.append("Phone: ").append(phone).append("\n");sb.append("Age: ").append(age).append("\n");inti=0;for(Carcar:cars){i++;sb.append("Car ").append(i).append(": ").append(car).append("\n");}returnsb.toString();}}
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:

{"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}

Cars json.svg

Since the Person's field age is marked as transient, it is not included in the output.

packagemain;importexample.Person;importcom.google.gson.Gson;publicclassMain{publicstaticvoidmain(String[]args){Gsongson=newGson();Stringjson="{\"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}";PersonjohnDoe=gson.fromJson(json,Person.class);System.out.println(johnDoe.toString());}}

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:

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

  • 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
  • How to convert Java field names

Related Research Articles

<span class="mw-page-title-main">Škoda Auto</span> Czech automobile manufacturer

Škoda Auto a.s., often shortened to Škoda, is a Czech automobile manufacturer established in 1925 as the successor to Laurin & Klement and headquartered in Mladá Boleslav, Czech Republic. Škoda Works became state owned in 1948. After 1991, it was gradually privatized to the German multinational conglomerate Volkswagen Group, becoming a partial subsidiary in 1994 and a wholly owned subsidiary in 2000.

In computing, serialization is the process of translating a data structure or object state into a format that can be stored or transmitted and reconstructed later. When the resulting series of bits is reread according to the serialization format, it can be used to create a semantically identical clone of the original object. For many complex objects, such as those that make extensive use of references, this process is not straightforward. Serialization of objects does not include any of their associated methods with which they were previously linked.

In object oriented programming, the factory method pattern is a design pattern that uses factory methods to deal with the problem of creating objects without having to specify their exact class. Rather than by calling a constructor, this is done by calling a factory method to create an object. Factory methods can either be specified in an interface and implemented by child classes, or implemented in a base class and optionally overridden by derived classes. It is one of the 23 classic design patterns described in the book Design Patterns and is sub-categorized as a creational pattern.

In software design and engineering, the observer pattern is a software design pattern in which an object, named the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods.

The Volkswagen Group A platform is an automobile platform shared among compact and mid-size cars of the Volkswagen Group.

<span class="mw-page-title-main">Volkswagen Group China</span> Division of Volkswagen Group in China

Volkswagen Group China is the Chinese subsidiary of the German automotive concern Volkswagen Group in the People's Republic of China.

<span class="mw-page-title-main">Škoda Superb</span> A large family car that has been produced by the Czech car manufacturer Škoda Auto

The Škoda Superb is a mid-size/large family car (D-segment) that has been produced by the Czech car manufacturer Škoda Auto since 2001.

<span class="mw-page-title-main">Group B</span> Motor racing regulations

Group B was a set of regulations for grand touring (GT) vehicles used in sports car racing and rallying introduced in 1982 by the Fédération Internationale de l'Automobile (FIA). Although permitted to enter a GT class of the World Sportscar Championship alongside the more popular racing prototypes of Group C, Group B are commonly associated with the international rallying scene during 1982 to 1986 in popular culture, when they were the highest class used across rallying, including the World Rally Championship, regional and national championships.

<span class="mw-page-title-main">Škoda Fabia</span> Supermini car produced by Czech manufacturer Škoda

The Škoda Fabia is a series of passenger cars produced by Czech manufacturer Škoda Auto since 1999. It is the successor of the Škoda Felicia, which was discontinued in 2001. The Fabia was available in hatchback, estate and saloon body styles at launch, and from 2007, the second generation was offered in hatchback and estate versions. The third generation Fabia was launched in 2015, and the fourth in 2021.

<span class="mw-page-title-main">Dependency injection</span> Software programming technique

In software engineering, dependency injection is a programming technique in which an object or function receives other objects or functions that it requires, as opposed to creating them internally. Dependency injection aims to separate the concerns of constructing objects and using them, leading to loosely coupled programs. The pattern ensures that an object or function that wants to use a given service should not have to know how to construct those services. Instead, the receiving 'client' is provided with its dependencies by external code, which it is not aware of. Dependency injection makes implicit dependencies explicit and helps solve the following problems:

<span class="mw-page-title-main">International Motor Show Germany</span> Annual German motor show

The International Motor Show Germany or International Mobility Show Germany, in German known as the Internationale Automobil-Ausstellung, is one of the world's largest mobility trade fairs. It consists of two separate fairs, that subdivided in 1991. While the IAA Mobility displays passenger vehicles, motorcycles and bikes, the IAA Transportation specializes in commercial vehicles. Before the separation, the show was held solely at the Messe Frankfurt.

<span class="mw-page-title-main">Škoda Octavia</span> Small family car produced by Škoda Auto

The Škoda Octavia is a small family car (C-segment) produced by the Czech car manufacturer Škoda Auto since the end of 1996. It shares its name with an earlier model produced between 1959 and 1971. Four generations of the modern-era Octavia model have been introduced to date, delivered with five-door liftback or five-door estate styles only. The car is front engined and both front- or four-wheel drive are offered. Around five million units have been sold in its two decades of presence on the market. The Octavia is Škoda's most popular model; about 40% of all newly manufactured Škoda cars are Octavias.

In the Java computer programming language, an annotation is a form of syntactic metadata that can be added to Java source code. Classes, methods, variables, parameters and Java packages may be annotated. Like Javadoc tags, Java annotations can be read from source files. Unlike Javadoc tags, Java annotations can also be embedded in and read from Java class files generated by the Java compiler. This allows annotations to be retained by the Java virtual machine at run-time and read via reflection. It is possible to create meta-annotations out of the existing ones in Java.

<span class="mw-page-title-main">C-segment</span> European car size classification

The C-segment is the 3rd category of the European segments for passenger cars and is described as "medium cars". It is equivalent to the Euro NCAP "small family car" size class, and the compact car category in the United States.

<span class="mw-page-title-main">SAIC Volkswagen</span> Chinese joint venture car company

SAIC Volkswagen Automotive Co., Ltd., formerly known as Shanghai Volkswagen Automotive Co., Ltd. is an automobile manufacturing company headquartered in Anting, Shanghai, China and a joint venture between SAIC Motor and Volkswagen Group. It was founded in 1984 and produces cars under the Volkswagen, Škoda and Audi marques. It is the second automobile manufacturing joint venture in China after American Motors and the first German car manufacturer to enter China.

<span class="mw-page-title-main">Volkswagen Group MQB platform</span> Motor vehicle platform

The Volkswagen Group MQB platform is the company's strategy for shared modular design construction of its transverse, front-engine, front-wheel-drive layout automobiles. It was first introduced in the Volkswagen Golf Mk7 in late 2012. Volkswagen spent roughly $8bn developing this new platform and the cars employing it. The platform underpins a wide range of cars from the supermini class to the mid size SUV class. MQB allows Volkswagen to assemble any of its cars based on this platform across all of its MQB ready factories. This allows the Volkswagen group flexibility to shift production as needed between its different factories. Beginning in 2012, Volkswagen Group marketed the strategy under the code name MQB, which stands for Modularer Querbaukasten, translating from German to "Modular Transversal Toolkit" or "Modular Transverse Matrix". MQB is one strategy within VW's overall MB program which also includes the similar MLB strategy for vehicles with longitudinal engine orientation.

Mockito is an open source testing framework for Java released under the MIT License. The framework allows the creation of test double objects in automated unit tests for the purpose of test-driven development (TDD) or behavior-driven development (BDD).

<span class="mw-page-title-main">Apache Avro</span> Open-source remote procedure call framework

Avro is a row-oriented remote procedure call and data serialization framework developed within Apache's Hadoop project. It uses JSON for defining data types and protocols, and serializes data in a compact binary format. Its primary use is in Apache Hadoop, where it can provide both a serialization format for persistent data, and a wire format for communication between Hadoop nodes, and from client programs to the Hadoop services. Avro uses a schema to structure the data that is being encoded. It has two different types of schema languages: one for human editing and another which is more machine-readable based on JSON.

<span class="mw-page-title-main">Automotive industry in Hungary</span>

Hungary significantly decreased the manufacturing of buses but found a large assembly capacities of foreign brands with annual production of more than 800 000 cars.

<span class="mw-page-title-main">Eurocar</span>

Eurocar PrJSC is the official manufacturer of Škoda cars in Ukraine, owned by Atoll Holding. It is one of the largest passenger car manufacturers in Ukraine. The plant's share in the total production of passenger vehicles in 2020 comprised 81%. The plant's production capacity amounts to 80 thousand cars per year with the potential for further capacity expansion. The production site has a railway terminal capable of transporting to the EU and CIS countries.

References

  1. "Release 2.11.0". 20 May 2024. Retrieved 22 June 2024.

[1]

[2]

Further reading

  1. More info on com.google.gson package (from javadoc.io)
  2. More info on Gson class (from javadoc.io)
  1. Jenkov, Jakob. "GSON - Gson". tutorials.jenkov.com. Retrieved 2023-12-28.
  2. Gson, Google, 2023-12-28, retrieved 2023-12-28