Gson (also known as Google Gson) is an open source Java library to serialize and deserialize Java objects to (and from) JSON.
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.8, was released on October 27, 2016.
October 27, 2016: Version 2.8.0June 14, 2016: Version 2.7February 26, 2016: Version 2.6.2February 11, 2016: Version 2.6.1February 11, 2016: Version 2.6Nov 24, 2015: Version 2.5Oct 4, 2015: Version 2.4Nov 20, 2014: Version 2.3.1Aug 11, 2014: Version 2.3May 13, 2013: Version 2.2.4April 12, 2013: Version 2.2.3July 2, 2012: Version 2.2.2May 5, 2012: Version 2.2.1May 5, 2012: Version 2.2December 31, 2011: Version 2.1November 13, 2011: Version 2.0April 13, 2011: Version 1.7.1April 12, 2011: Version 1.7November 24, 2010: Version 1.6August 19, 2010: Version 1.5October 9, 2009: Version 1.4April 1, 2009: Version 1.3January 12, 2009: Version 1.3 BetaAugust 29, 2008: Version 1.2July 18, 2008: Version 1.1.1July 1, 2008: Version 1.1June 17, 2008: Version 1.0.1May 22, 2008: Version 1.0Gson uses reflection so it does not require additional modifications to classes of (de)serialized objects. In fact it just needs the class to have defined default no-args constructor (not entirely true, see Features).
The following example demonstrates the most basic usage of Gson when serializing a sample object:
After calling
you will get this 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:
And the following output will be generated:
Gson can handle collections, generic types and nested classes (including inner classes, this can not be done by default though)When deserializing, Gson is navigating the type tree of the object, which is 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 outputRules of what fields are intended to be excluded from (de)serializationHow to convert Java field names