Gson

Last updated
Google Gson
Developer(s) Google
Initial releaseMay 22, 2008;17 years ago (2008-05-22)
Stable release
2.13.1 [1]   OOjs UI icon edit-ltr-progressive.svg / 24 April 2025;3 months ago (24 April 2025)
Repository
Written in Java
Operating system Cross-platform
License Apache License 2.0
Website github.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).

Contents

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.

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:

  packageexample;    publicclassCar{  publicStringmanufacturer;  publicStringmodel;  publicdoublecapacity;  publicbooleanaccident;    publicCar(){  }    publicCar(Stringmanufacturer,Stringmodel,doublecapacity,booleanaccident){  this.manufacturer=manufacturer;  this.model=model;  this.capacity=capacity;  this.accident=accident;  }    @Override  publicStringtoString(){  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;  }    @Override  publicStringtoString(){  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 JSON  Gsongson=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 above Main 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": "Skoda", "model": "Octavia", "capacity": 2.0, "accident": true } ], "phone": 2025550191 } Cars json.svg
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 field age is marked as transient, 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 the Java 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 their GitHub repository.

Features

  • 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

  1. "Release 2.13.1". 24 April 2025. Retrieved 21 May 2025.

Further reading

  1. More info on com.google.gson package (from javadoc.io)
  2. More info on Gson class (from javadoc.io)