This article has multiple issues. Please helpimprove it or discuss these issues on thetalk page.(Learn how and when to remove these messages) (Learn how and when to remove this message)
|
| Google Gson | |
|---|---|
| Developer | |
| Initial release | May 22, 2008; 17 years ago (2008-05-22) |
| Stable release | |
| Repository | |
| Written in | Java |
| Operating system | Cross-platform |
| License | Apache License 2.0 |
| Website | github |
Gson, or Google Gson, is anopen-sourceJava library that serializes Java objects toJSON (and deserializes them back to Java).
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.
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:

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