Gson: Difference between revisions
m Dating maintenance tags: {{Unreferenced}} |
|||
(32 intermediate revisions by 20 users not shown) | |||
Line 1: | Line 1: | ||
{{Short description|Open-source Java library to serialize and deserialize Java objects to and from JSON}} |
|||
{{unreferenced|date=August 2020}} |
|||
{{Multiple issues| |
|||
{{Tone|date=November 2023}} |
|||
{{More citations needed|date=November 2023}} |
|||
}} |
|||
{{Infobox software |
{{Infobox software |
||
| name |
| name = Google Gson |
||
| logo |
| logo = |
||
| screenshot |
| screenshot = |
||
| caption |
| caption = |
||
| developer |
| developer = [[Google]] |
||
| released |
| released = {{Start date and age|2008|05|22}} |
||
| latest release version = |
| latest release version = {{wikidata|property|reference|edit|P348}} |
||
| latest release date |
| latest release date = {{Start date and age|{{Wikidata|qualifier|P348|P577}}|df=yes}} |
||
| programming language |
| programming language = [[Java (programming language)|Java]] |
||
| operating system |
| operating system = [[Cross-platform]] |
||
| license |
| license = [[Apache License 2.0]] |
||
| website |
| website = {{url|https://github.com/google/gson}} |
||
}} |
}} |
||
{{Portal|Free and open-source software|Computer programming}} |
{{Portal|Free and open-source software|Computer programming}} |
||
'''Gson''' |
'''Gson''', or Google Gson, is an [[Open-source software|open-source]] [[Java (programming language)|Java]] library that serializes Java objects to [[JSON]] (and deserializes them back to Java). |
||
==History== |
==History== |
||
The Gson library was originally developed for internal purposes |
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. |
||
==Version history== |
|||
* Oct 04, 2019: Version 2.8.6 |
|||
* May 21, 2018: Version 2.8.5 |
|||
* May 1, 2018: Version 2.8.4 |
|||
* April 27, 2018: Version 2.8.3 |
|||
* Sept 19, 2017: Version 2.8.2 |
|||
* May 30, 2017: Version 2.8.1 |
|||
* October 27, 2016: Version 2.8.0 |
|||
* June 14, 2016: Version 2.7 |
|||
* February 26, 2016: Version 2.6.2 |
|||
* February 11, 2016: Version 2.6.1 |
|||
* February 11, 2016: Version 2.6 |
|||
* Nov 24, 2015: Version 2.5 |
|||
* Oct 4, 2015: Version 2.4 |
|||
* Nov 20, 2014: Version 2.3.1 |
|||
* Aug 11, 2014: Version 2.3 |
|||
* May 13, 2013: Version 2.2.4 |
|||
* April 12, 2013: Version 2.2.3 |
|||
* July 2, 2012: Version 2.2.2 |
|||
* May 5, 2012: Version 2.2.1 |
|||
* May 5, 2012: Version 2.2 |
|||
* December 31, 2011: Version 2.1 |
|||
* November 13, 2011: Version 2.0 |
|||
* April 13, 2011: Version 1.7.1 |
|||
* April 12, 2011: Version 1.7 |
|||
* November 24, 2010: Version 1.6 |
|||
* August 19, 2010: Version 1.5 |
|||
* October 9, 2009: Version 1.4 |
|||
* April 1, 2009: Version 1.3 |
|||
* January 12, 2009: Version 1.3 Beta |
|||
* August 29, 2008: Version 1.2 |
|||
* July 18, 2008: Version 1.1.1 |
|||
* July 1, 2008: Version 1.1 |
|||
* June 17, 2008: Version 1.0.1 |
|||
* May 22, 2008: Version 1.0 |
|||
==Usage== |
==Usage== |
||
Gson |
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|Features]]). |
||
The following example demonstrates the |
The following example demonstrates the basic usage of Gson when serializing a sample object: |
||
<syntaxhighlight lang="java"> |
|||
module GsonExample { |
|||
requires gson; |
|||
requires java.sql; // Required by gson |
|||
exports Person; |
|||
exports Car; |
|||
} |
|||
</syntaxhighlight> |
|||
<syntaxhighlight lang="java"> |
<syntaxhighlight lang="java"> |
||
package |
package example; |
||
public class Car { |
public class Car { |
||
Line 94: | Line 54: | ||
</syntaxhighlight> |
</syntaxhighlight> |
||
<syntaxhighlight lang="java"> |
<syntaxhighlight lang="java"> |
||
package |
package example; |
||
import Car.Car; |
|||
public class Person { |
public class Person { |
||
Line 123: | Line 81: | ||
sb.append("Age: ").append(age).append("\n"); |
sb.append("Age: ").append(age).append("\n"); |
||
int i = 0; |
int i = 0; |
||
for (Car |
for (Car car : cars) { |
||
i++; |
i++; |
||
sb.append("Car ").append(i).append(": ").append( |
sb.append("Car ").append(i).append(": ").append(car).append("\n"); |
||
} |
} |
||
return sb.toString(); |
return sb.toString(); |
||
} |
} |
||
} |
} |
||
</syntaxhighlight> |
</syntaxhighlight><syntaxhighlight lang="java"> |
||
package main; |
|||
import example.Car; |
|||
After calling |
|||
import example.Person; |
|||
<syntaxhighlight lang="java"> |
|||
package Main; |
|||
import Car.Car; |
|||
import Person.Person; |
|||
import com.google.gson.Gson; |
import com.google.gson.Gson; |
||
import com.google.gson.GsonBuilder; |
|||
public class Main { |
public class Main { |
||
public static void main(String[] args) { |
public static void main(String[] args) { |
||
// Enable pretty printing for demonstration purposes |
|||
Gson gson = new Gson(); |
|||
// 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 audi = new Car("Audi", "A4", 1.8, false); |
||
Car skoda = new Car("Škoda", "Octavia", 2.0, true); |
Car skoda = new Car("Škoda", "Octavia", 2.0, true); |
||
Line 152: | Line 110: | ||
</syntaxhighlight> |
</syntaxhighlight> |
||
Calling the code of the above ''Main'' class will result in the following JSON output: |
|||
you will get this output: |
|||
<syntaxhighlight lang="json"> |
<syntaxhighlight lang="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 |
|||
} |
} |
||
</syntaxhighlight> |
</syntaxhighlight> |
||
[[File:Cars json.svg|Diagram featuring data from JSON.]] |
|||
Since the Person's field "age" is marked as transient, it is not included in the output. |
|||
Since the Person's field ''age'' is marked as ''transient'', it is not included in the output.<syntaxhighlight lang="java"> |
|||
To deserialize output produced by last example, you can execute the following code: |
|||
package main; |
|||
<syntaxhighlight lang="java"> |
|||
package Main; |
|||
import |
import example.Person; |
||
import com.google.gson.Gson; |
import com.google.gson.Gson; |
||
Line 196: | Line 153: | ||
</syntaxhighlight> |
</syntaxhighlight> |
||
To deserialize the output produced by the last example, you can execute the code above, which generates the following output: |
|||
And the following output will be generated: |
|||
<syntaxhighlight lang=" |
<syntaxhighlight lang="output"> |
||
Name: John Doe |
Name: John Doe |
||
Phone: 2025550191 |
Phone: 2025550191 |
||
Line 205: | Line 162: | ||
</syntaxhighlight> |
</syntaxhighlight> |
||
This shows how Gson can be used with the [[Java Platform Module System]] for the example above: |
|||
The following example demonstrates how to pretty print a Json using Gson library. |
|||
<syntaxhighlight lang="java"> |
<syntaxhighlight lang="java"> |
||
module GsonExample { |
|||
import com.google.gson.Gson; |
|||
requires com.google.gson; |
|||
// Open package declared in the example above to allow Gson to use reflection on classes |
|||
import java.nio.file.Files; |
|||
// inside the package (and also access non-public fields) |
|||
import java.nio.file.Paths; |
|||
opens example to com.google.gson; |
|||
import java.util.Arrays; |
|||
import java.util.List; |
|||
import lombok.SneakyThrows; |
|||
public class PrettyPrintExample { |
|||
//SneakyThrows annotation will internally declare all checked exceptions. |
|||
@SneakyThrows |
|||
public static void main(String[] args) { |
|||
List<String> cars= Arrays.asList("Fiat","BMW","Lamborghini"); |
|||
//Create new GSON object |
|||
Gson gson = new GsonBuilder().setPrettyPrinting().create(); |
|||
String prettyJson=gson.toJson(cars); |
|||
System.out.println("pretty "+prettyJson); |
|||
} |
|||
} |
} |
||
</syntaxhighlight> |
</syntaxhighlight> |
||
For more extensive examples, see Gson's usage guide on their [https://github.com/google/gson GitHub repository]. |
|||
And the following output will be generated: |
|||
<syntaxhighlight lang="text"> |
|||
pretty [ |
|||
"Fiat", |
|||
"BMW", |
|||
"Lamborghini" |
|||
] |
|||
</syntaxhighlight> |
|||
==Features== |
==Features== |
||
* Gson can handle collections, generic types and nested classes (including inner classes, |
* 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 |
* 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: |
|||
* User can write a custom serializer and/or deserializer so that they can control the whole process and even (de)serialize instances of classes for which the source code is not accessible. |
|||
* |
** 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, you can specify: |
|||
* Gson is highly customizable, as you can specify: |
|||
:* Compact/pretty printing (whether you want compact or readable output) |
:* Compact/pretty printing (whether you want compact or readable output) |
||
:* How to handle null object fields |
:* 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 |
:* How to convert Java field names |
||
== References == |
|||
<references /><ref>{{Cite web |last=Jenkov |first=Jakob |title=GSON - Gson |url=http://tutorials.jenkov.com/tutorials/java-json/gson.html |access-date=2023-12-28 |website=tutorials.jenkov.com}}</ref> |
|||
<ref>{{Citation |title=Gson |date=2023-12-28 |url=https://github.com/google/gson |access-date=2023-12-28 |publisher=Google}}</ref> |
|||
==External links== |
==External links== |
||
* [https://github.com/google/gson/ Gson on GitHub] |
* [https://github.com/google/gson/ Gson on GitHub] |
||
* [https://thecodingbrains.com/gson-tutorials-with-code-examples/ Gson tutorial with examples] |
* [https://thecodingbrains.com/gson-tutorials-with-code-examples/ Gson tutorial with examples] {{Webarchive|url=https://web.archive.org/web/20201031164526/https://thecodingbrains.com/gson-tutorials-with-code-examples/ |date=2020-10-31 }} |
||
== Further reading == |
|||
# [https://javadoc.io/doc/com.google.code.gson/gson More info on ''com.google.gson'' package (from '''javadoc.io''')] |
|||
# [https://javadoc.io/doc/com.google.code.gson/gson/latest/com.google.gson/com/google/gson/Gson.html More info on ''Gson'' class (from '''javadoc.io''')] |
|||
{{Google FOSS}} |
{{Google FOSS}} |
||
Line 259: | Line 203: | ||
[[Category:JSON]] |
[[Category:JSON]] |
||
[[Category:Google software]] |
[[Category:Google software]] |
||
[[Category: |
[[Category:2008 software]] |
Revision as of 09:47, 7 May 2024
![]() | This article has multiple issues. Please help improve it or discuss these issues on the talk page. (Learn how and when to remove these template messages)
|
Developer(s) | |
---|---|
Initial release | May 22, 2008 |
Stable release | 2.11.0[1] ![]() |
Repository | |
Written in | Java |
Operating system | Cross-platform |
License | Apache License 2.0 |
Website | github |
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.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:
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 example.Car;
import example.Person;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
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:
{
"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 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 {
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, you can execute the code above, which 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: true
This 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.
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
- How to convert Java field names
References
- ^ "Release 2.11.0". 20 May 2024. Retrieved 22 June 2024.
External links
- Gson on GitHub
- Gson tutorial with examples Archived 2020-10-31 at the Wayback Machine
Further reading
- ^ Jenkov, Jakob. "GSON - Gson". tutorials.jenkov.com. Retrieved 2023-12-28.
- ^ Gson, Google, 2023-12-28, retrieved 2023-12-28