Jump to content
 







Main menu
   


Navigation  



Main page
Contents
Current events
Random article
About Wikipedia
Contact us
Donate
 




Contribute  



Help
Learn to edit
Community portal
Recent changes
Upload file
 








Search  

































Create account

Log in
 









Create account
 Log in
 




Pages for logged out editors learn more  



Contributions
Talk
 



















Contents

   



(Top)
 


1 History  





2 Usage  





3 Features  





4 References  





5 External links  





6 Further reading  














Gson






Deutsch
Español


 

Edit links
 









Article
Talk
 

















Read
Edit
View history
 








Tools
   


Actions  



Read
Edit
View history
 




General  



What links here
Related changes
Upload file
Special pages
Permanent link
Page information
Cite this page
Get shortened URL
Download QR code
Wikidata item
 




Print/export  



Download as PDF
Printable version
 
















Appearance
   

 






From Wikipedia, the free encyclopedia
 


Google Gson
Developer(s)Google
Initial releaseMay 22, 2008; 16 years ago (2008-05-22)
Stable release

2.11.0[1] Edit this on Wikidata / 20 May 2024; 53 days ago (20 May 2024)

Repository
Written inJava
Operating systemCross-platform
LicenseApache License 2.0
Websitegithub.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).

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 the Apache License 2.0. The latest version, 2.10.1, was released on January 6, 2023.

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

Diagram featuring data from JSON.

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[edit]

  • 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.11.0". 20 May 2024. Retrieved 22 June 2024.

[1]

[2]

External links[edit]

Further reading[edit]

  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.
  • ^ Gson, Google, 2023-12-28, retrieved 2023-12-28

  • Retrieved from "https://en.wikipedia.org/w/index.php?title=Gson&oldid=1231511139"

    Categories: 
    Java (programming language) libraries
    JSON
    Google software
    2008 software
    Hidden categories: 
    Articles with short description
    Short description matches Wikidata
    Wikipedia articles with style issues from November 2023
    All articles with style issues
    Articles needing additional references from November 2023
    All articles needing additional references
    Articles with multiple maintenance issues
    Webarchive template wayback links
     



    This page was last edited on 28 June 2024, at 17:56 (UTC).

    Text is available under the Creative Commons Attribution-ShareAlike License 4.0; additional terms may apply. By using this site, you agree to the Terms of Use and Privacy Policy. Wikipedia® is a registered trademark of the Wikimedia Foundation, Inc., a non-profit organization.



    Privacy policy

    About Wikipedia

    Disclaimers

    Contact Wikipedia

    Code of Conduct

    Developers

    Statistics

    Cookie statement

    Mobile view



    Wikimedia Foundation
    Powered by MediaWiki