# Gson User Guide
1. [Overview](#TOC-Overview)
2. [Goals for Gson](#TOC-Goals-for-Gson)
3. [Gson Performance and Scalability](#TOC-Gson-Performance-and-Scalability)
4. [Gson Users](#TOC-Gson-Users)
5. [Using Gson](#TOC-Using-Gson)
* [Using Gson with Gradle/Android](#TOC-Gson-With-Gradle)
* [Using Gson with Maven](#TOC-Gson-With-Maven)
* [Primitives Examples](#TOC-Primitives-Examples)
* [Object Examples](#TOC-Object-Examples)
* [Finer Points with Objects](#TOC-Finer-Points-with-Objects)
* [Nested Classes (including Inner Classes)](#TOC-Nested-Classes-including-Inner-Classes-)
* [Array Examples](#TOC-Array-Examples)
* [Collections Examples](#TOC-Collections-Examples)
* [Collections Limitations](#TOC-Collections-Limitations)
* [Maps Examples](#TOC-Maps-Examples)
* [Serializing and Deserializing Generic Types](#TOC-Serializing-and-Deserializing-Generic-Types)
* [Serializing and Deserializing Collection with Objects of Arbitrary Types](#TOC-Serializing-and-Deserializing-Collection-with-Objects-of-Arbitrary-Types)
* [Built-in Serializers and Deserializers](#TOC-Built-in-Serializers-and-Deserializers)
* [Custom Serialization and Deserialization](#TOC-Custom-Serialization-and-Deserialization)
* [Writing a Serializer](#TOC-Writing-a-Serializer)
* [Writing a Deserializer](#TOC-Writing-a-Deserializer)
* [Writing an Instance Creator](#TOC-Writing-an-Instance-Creator)
* [InstanceCreator for a Parameterized Type](#TOC-InstanceCreator-for-a-Parameterized-Type)
* [Compact Vs. Pretty Printing for JSON Output Format](#TOC-Compact-Vs.-Pretty-Printing-for-JSON-Output-Format)
* [Null Object Support](#TOC-Null-Object-Support)
* [Versioning Support](#TOC-Versioning-Support)
* [Excluding Fields From Serialization and Deserialization](#TOC-Excluding-Fields-From-Serialization-and-Deserialization)
* [Java Modifier Exclusion](#TOC-Java-Modifier-Exclusion)
* [Gson's `@Expose`](#TOC-Gson-s-Expose)
* [User Defined Exclusion Strategies](#TOC-User-Defined-Exclusion-Strategies)
* [JSON Field Naming Support](#TOC-JSON-Field-Naming-Support)
* [Sharing State Across Custom Serializers and Deserializers](#TOC-Sharing-State-Across-Custom-Serializers-and-Deserializers)
* [Streaming](#TOC-Streaming)
6. [Issues in Designing Gson](#TOC-Issues-in-Designing-Gson)
7. [Future Enhancements to Gson](#TOC-Future-Enhancements-to-Gson)
## Overview
Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object.
Gson can work with arbitrary Java objects including pre-existing objects that you do not have source code of.
## Goals for Gson
* Provide easy to use mechanisms like `toString()` and constructor (factory method) to convert Java to JSON and vice-versa
* Allow pre-existing unmodifiable objects to be converted to and from JSON
* Allow custom representations for objects
* Support arbitrarily complex objects
* Generate compact and readable JSON output
## Gson Performance and Scalability
Here are some metrics that we obtained on a desktop (dual opteron, 8GB RAM, 64-bit Ubuntu) running lots of other things along-with the tests. You can rerun these tests by using the class [`PerformanceTest`](gson/src/test/java/com/google/gson/metrics/PerformanceTest.java).
* Strings: Deserialized strings of over 25MB without any problems (see `disabled_testStringDeserializationPerformance` method in `PerformanceTest`)
* Large collections:
* Serialized a collection of 1.4 million objects (see `disabled_testLargeCollectionSerialization` method in `PerformanceTest`)
* Deserialized a collection of 87,000 objects (see `disabled_testLargeCollectionDeserialization` in `PerformanceTest`)
* Gson 1.4 raised the deserialization limit for byte arrays and collection to over 11MB from 80KB.
Note: Delete the `disabled_` prefix to run these tests. We use this prefix to prevent running these tests every time we run JUnit tests.
## Gson Users
Gson was originally created for use inside Google where it is currently used in a number of projects. It is now used by a number of public projects and companies.
## Using Gson
The primary class to use is [`Gson`](gson/src/main/java/com/google/gson/Gson.java) which you can just create by calling `new Gson()`. There is also a class [`GsonBuilder`](gson/src/main/java/com/google/gson/GsonBuilder.java) available that can be used to create a Gson instance with various settings like version control and so on.
The Gson instance does not maintain any state while invoking JSON operations. So, you are free to reuse the same object for multiple JSON serialization and deserialization operations.
## Using Gson with Gradle/Android
```gradle
dependencies {
implementation 'com.google.code.gson:gson:2.10'
}
```
## Using Gson with Maven
To use Gson with Maven2/3, you can use the Gson version available in Maven Central by adding the following dependency:
```xml
com.google.code.gson
gson
2.10
compile
```
That is it, now your Maven project is Gson enabled.
### Primitives Examples
```java
// Serialization
Gson gson = new Gson();
gson.toJson(1); // ==> 1
gson.toJson("abcd"); // ==> "abcd"
gson.toJson(new Long(10)); // ==> 10
int[] values = { 1 };
gson.toJson(values); // ==> [1]
// Deserialization
int one = gson.fromJson("1", int.class);
Integer one = gson.fromJson("1", Integer.class);
Long one = gson.fromJson("1", Long.class);
Boolean false = gson.fromJson("false", Boolean.class);
String str = gson.fromJson("\"abc\"", String.class);
String[] anotherStr = gson.fromJson("[\"abc\"]", String[].class);
```
### Object Examples
```java
class BagOfPrimitives {
private int value1 = 1;
private String value2 = "abc";
private transient int value3 = 3;
BagOfPrimitives() {
// no-args constructor
}
}
// Serialization
BagOfPrimitives obj = new BagOfPrimitives();
Gson gson = new Gson();
String json = gson.toJson(obj);
// ==> json is {"value1":1,"value2":"abc"}
```
Note that you can not serialize objects with circular references since that will result in infinite recursion.
```java
// Deserialization
BagOfPrimitives obj2 = gson.fromJson(json, BagOfPrimitives.class);
// ==> obj2 is just like obj
```
#### **Finer Points with Objects**
* It is perfectly fine (and recommended) to use private fields.
* There is no need to use any annotations to indicate a field is to be included for serialization and deserialization. All fields in the current class (and from all super classes) are included by default.
* If a field is marked transient, (by default) it is ignored and not included in the JSON serialization or deserialization.
* This implementation handles nulls correctly.
* While serializing, a null field is omitted from the output.
* While deserializing, a missing entry in JSON results in setting the corresponding field in the object to its default value: null for object types, zero for numeric types, and false for booleans.
* If a field is _synthetic_, it is ignored and not included in JSON serialization or deserialization.
* Fields corresponding to the outer classes in inner classes are ignored and not included in serialization or deserialization.
* Anonymous and local classes are excluded. They will be serialized as JSON `null` and when deserialized their JSON value is ignored and `null` is returned. Convert the classes to `static` nested classes to enable serialization and deserialization for them.
### Nested Classes (including Inner Classes)
Gson can serialize static nested classes quite easily.
Gson can also deserialize static nested classes. However, Gson can **not** automatically deserialize the **pure inner classes since their no-args constructor also need a reference to the containing Object** which is not available at the time of deserialization. You can address this problem by either making the inner class static or by providing a custom InstanceCreator for it. Here is an example:
```java
public class A {
public String a;
class B {
public String b;
public B() {
// No args constructor for B
}
}
}
```
**NOTE**: The above class B can not (by default) be serialized with Gson.
Gson can not deserialize `{"b":"abc"}` into an instance of B since the class B is an inner class. If it was defined as static class B then Gson would have been able to deserialize the string. Another solution is to write a custom instance creator for B.
```java
public class InstanceCreatorForB implements InstanceCreator {
private final A a;
public InstanceCreatorForB(A a) {
this.a = a;
}
public A.B createInstance(Type type) {
return a.new B();
}
}
```
The above is possible, but not recommended.
### Array Examples
```java
Gson gson = new Gson();
int[] ints = {1, 2, 3, 4, 5};
String[] strings = {"abc", "def", "ghi"};
// Serialization
gson.toJson(ints); // ==> [1,2,3,4,5]
gson.toJson(strings); // ==> ["abc", "def", "ghi"]
// Deserialization
int[] ints2 = gson.fromJson("[1,2,3,4,5]", int[].class);
// ==> ints2 will be same as ints
```
We also support multi-dimensional arrays, with arbitrarily complex element types.
### Collections Examples
```java
Gson gson = new Gson();
Collection ints = Arrays.asList(1,2,3,4,5);
// Serialization
String json = gson.toJson(ints); // ==> json is [1,2,3,4,5]
// Deserialization
TypeToken> collectionType = new TypeToken>(){};
// Note: For older Gson versions it is necessary to use `collectionType.getType()` as argument below,
// this is however not type-safe and care must be taken to specify the correct type for the local variable
Collection ints2 = gson.fromJson(json, collectionType);
// ==> ints2 is same as ints
```
Fairly hideous: note how we define the type of collection.
Unfortunately, there is no way to get around this in Java.
#### Collections Limitations
Gson can serialize collection of arbitrary objects but can not deserialize from it, because there is no way for the user to indicate the type of the resulting object. Instead, while deserializing, the Collection must be of a specific, generic type.
This makes sense, and is rarely a problem when following good Java coding practices.
### Maps Examples
Gson by default serializes any `java.util.Map` implementation as a JSON object. Because JSON objects only support strings as member names, Gson converts the Map keys to strings by calling `toString()` on them, and using `"null"` for `null` keys:
```java
Gson gson = new Gson();
Map stringMap = new LinkedHashMap<>();
stringMap.put("key", "value");
stringMap.put(null, "null-entry");
// Serialization
String json = gson.toJson(stringMap); // ==> json is {"key":"value","null":"null-entry"}
Map intMap = new LinkedHashMap<>();
intMap.put(2, 4);
intMap.put(3, 6);
// Serialization
String json = gson.toJson(intMap); // ==> json is {"2":4,"3":6}
```
For deserialization Gson uses the `read` method of the `TypeAdapter` registered for the Map key type. Similar to the Collection example shown above, for deserialization a `TypeToken` has to be used to tell Gson what types the Map keys and values have:
```java
Gson gson = new Gson();
TypeToken