Gson - Overview


Google Gson is a simple Java-based library to serialize Java objects to JSON and vice versa. It is an open-source library developed by Google.

The following points highlight why you should be using this library −

  • Standardized − Gson is a standardized library that is managed by Google.

  • Efficient − It is a reliable, fast, and efficient extension to the Java standard library.

  • Optimized − The library is highly optimized.

  • Support Generics − It provides extensive support for generics.

  • Supports complex inner classes − It supports complex objects with deep inheritance hierarchies.

Features of Gson

Here is a list of some of the most prominent features of Gson −

  • Easy to use − Gson API provides a high-level facade to simplify commonly used use-cases.

  • No need to create mapping − Gson API provides default mapping for most of the objects to be serialized.

  • Performance − Gson is quite fast and is of low memory footprint. It is suitable for large object graphs or systems.

  • Clean JSON − Gson creates a clean and compact JSON result which is easy to read.

  • No Dependency − Gson library does not require any other library apart from JDK.

  • Open Source − Gson library is open source; it is freely available.

Three Ways of Processing JSON

Gson provides three alternative ways to process JSON −

Streaming API

It reads and writes JSON content as discrete events. JsonReader and JsonWriter read/write the data as token, referred as JsonToken.

It is the most powerful approach among the three approaches to process JSON. It has the lowest overhead and it is quite fast in read/write operations. It is analogous to Stax parser for XML.

Tree Model

It prepares an in-memory tree representation of the JSON document. It builds a tree of JsonObject nodes. It is a flexible approach and is analogous to DOM parser for XML.

Data Binding

It converts JSON to and from POJO (Plain Old Java Object) using property accessor. Gson reads/writes JSON using data type adapters. It is analogous to JAXB parser for XML.