Jump to content

Gson: Difference between revisions

From Wikipedia, the free encyclopedia
Content deleted Content added
m →‎Usage: lang="output"
Update usage example code: Place module-info.java code last because it is optional (and update it to use correct module name); use more conventional package names; update actually produced JSON output; remove separate pretty-printing example
Line 62: Line 62:


==Usage==
==Usage==
Gson uses [[reflection (computer science)|reflection]], so it does not require classes being serialized or de-serialized to be modified. By default, it just needs the class to have defined default no-args constructor (which can be worked around, see [[#Features|Features]]).
Gson uses [[reflection (computer science)|reflection]], so it does not require classes being serialized or de-serialized to be modified. By default, it just needs the class to have defined a default no-args constructor (which can be worked around, see [[#Features|Features]]).


The following example demonstrates the most basic usage of Gson when serializing a sample object:
The following example demonstrates the most basic usage of Gson when serializing a sample object:
<syntaxhighlight lang="java">
<syntaxhighlight lang="java">
package example;
module GsonExample {
requires gson;
requires java.sql; // Required by gson
exports Person;
exports Car;
}
</syntaxhighlight>
<syntaxhighlight lang="java">
package Car;


public class Car {
public class Car {
Line 99: Line 91:
</syntaxhighlight>
</syntaxhighlight>
<syntaxhighlight lang="java">
<syntaxhighlight lang="java">
package Person;
package example;

import Car.Car;


public class Person {
public class Person {
Line 128: Line 118:
sb.append("Age: ").append(age).append("\n");
sb.append("Age: ").append(age).append("\n");
int i = 0;
int i = 0;
for (Car item : cars) {
for (Car car : cars) {
i++;
i++;
sb.append("Car ").append(i).append(": ").append(item).append("\n");
sb.append("Car ").append(i).append(": ").append(car).append("\n");
}
}
return sb.toString();
return sb.toString();
Line 137: Line 127:
</syntaxhighlight>
</syntaxhighlight>


After calling
After calling the code of the following Main class:
<syntaxhighlight lang="java">
<syntaxhighlight lang="java">
package Main;
package main;


import Car.Car;
import example.Car;
import Person.Person;
import example.Person;
import com.google.gson.Gson;
import com.google.gson.Gson;


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 157: Line 149:
</syntaxhighlight>
</syntaxhighlight>


you will get this output:
You will get this JSON output:
<syntaxhighlight lang="json">
<syntaxhighlight lang="json">
{
{
"name":"John",
"name": "John",
"surname":"Doe",
"surname": "Doe",
"cars":[
"cars": [
{
{
"manufacturer":"Audi",
"manufacturer": "Audi",
"model":"A4",
"model": "A4",
"capacity":1.8,
"capacity": 1.8,
"accident":false
"accident": false
},
},
{
{
"manufacturer":"Škoda",
"manufacturer": "Škoda",
"model":"Octavia",
"model": "Octavia",
"capacity":2.0,
"capacity": 2.0,
"accident":true
"accident": true
}
}
],
],
"phone":2025550191
"phone": 2025550191
}
}
</syntaxhighlight>
</syntaxhighlight>
Line 182: Line 174:
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.


To deserialize output produced by last example, you can execute the following code:
To deserialize the output produced by the last example, you can execute the following code:
<syntaxhighlight lang="java">
<syntaxhighlight lang="java">
package Main;
package main;


import Person.Person;
import example.Person;
import com.google.gson.Gson;
import com.google.gson.Gson;


Line 210: Line 202:
</syntaxhighlight>
</syntaxhighlight>


For the above example the following shows how Gson can be used with the [[Java Platform Module System]]:
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;
import com.google.gson.GsonBuilder;
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>


See Gson's usage guide on their GitHub repository for more extensive examples.
And the following output will be generated:
<syntaxhighlight lang="output">
pretty [
"Fiat",
"BMW",
"Lamborghini"
]
</syntaxhighlight>


==Features==
==Features==

Revision as of 16:30, 26 July 2022

Google Gson
Developer(s)Google
Initial releaseMay 22, 2008; 16 years ago (2008-05-22)
Stable release
2.9.0 / 12 February 2022; 2 years ago (2022-02-12)
Repository
Written inJava
Operating systemCross-platform
LicenseApache License 2.0
Websitegithub.com/google/gson

Gson (also known as Google Gson) is an open-source Java library to serialize and deserialize Java objects to (and from) JSON.

History

The Gson library was originally developed for internal purposes of Google, and Version 1.0 was later released on May 22, 2008 under the terms of Apache License 2.0. The latest version, 2.9.0, was released on Feb 12, 2022.

Version history

  • Feb 12, 2022: Version 2.9.0
  • Oct 30, 2021: Version 2.8.9
  • Aug 20, 2021: Version 2.8.8
  • May 25, 2021: Version 2.8.7
  • 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

Gson uses reflection, so it does not require classes being serialized or de-serialized to be modified. By default, it just needs the class to have defined a default no-args constructor (which can be worked around, see Features).

The following example demonstrates the most 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();
    }
}

After calling the code of the following Main class:

package main;

import example.Car;
import example.Person;
import com.google.gson.Gson;

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));
    }
}

You will get this 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.

To deserialize the output produced by the last example, you can execute the following code:

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());
    }
}

And the following output will be generated:

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

For the above example the following shows how Gson can be used with the Java Platform Module System:

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;
}

See Gson's usage guide on their GitHub repository for more extensive examples.

Features

  • Gson can handle collections, generic types and nested classes (including inner classes, this can not be done by default though)
  • When deserializing, Gson navigates the type tree of the object being deserialized. This results in ignoring extra fields present in the JSON input.
  • 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.
  • User can write an InstanceCreator which allows them to deserialize instances of classes without a defined no-args constructor.
  • Gson is highly customizable, 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
  • Rules of what fields are intended to be excluded from (de)serialization
  • How to convert Java field names

External links