Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikipediaThe Free Encyclopedia
Search

Gson

From Wikipedia, the free encyclopedia
Java JSON serialization library
This article has multiple issues. Please helpimprove it or discuss these issues on thetalk page.(Learn how and when to remove these messages)
This article'stone or style may not reflect theencyclopedic tone used on Wikipedia. See Wikipedia'sguide to writing better articles for suggestions.(November 2023) (Learn how and when to remove this message)
icon
This articleneeds additional citations forverification. Please helpimprove this article byadding citations to reliable sources. Unsourced material may be challenged and removed.
Find sources: "Gson" – news ·newspapers ·books ·scholar ·JSTOR
(November 2023) (Learn how and when to remove this message)
(Learn how and when to remove this message)
Google Gson
DeveloperGoogle
Initial releaseMay 22, 2008; 17 years ago (2008-05-22)
Stable release
2.13.2[1] Edit this on Wikidata / 10 September 2025; 2 months ago (10 September 2025)
Repository
Written inJava
Operating systemCross-platform
LicenseApache License 2.0
Websitegithub.com/google/gson

Gson, or Google Gson, is anopen-sourceJava library that serializes Java objects toJSON (and deserializes them back to Java).

History

[edit]

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

Usage

[edit]

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 (seeFeatures).

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 aboveMain class will result in the following JSON output:

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}

Since the Person's fieldage is marked astransient, 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 theJava 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 theirGitHub repository.

Features

[edit]
  • Gson can handlecollections,generic types, andnested classes (includinginner classes, which cannot be done by default).
  • When deserializing, Gson navigates thetype 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
  • How to convert Java field names

References

[edit]
  1. ^"Release 2.13.2". 10 September 2025. Retrieved15 September 2025.
  • Jenkov, Jakob."GSON - Gson".tutorials.jenkov.com. Retrieved2023-12-28.
  • Gson, Google, 2023-12-28, retrieved2023-12-28

Further reading

[edit]

External links

[edit]
Google free and open-source software
Software
Applications
Programming languages
Frameworks and
development tools
Operating systems
Related
Retrieved from "https://en.wikipedia.org/w/index.php?title=Gson&oldid=1319616430"
Categories:
Hidden categories:

[8]ページ先頭

©2009-2025 Movatter.jp