This article is compiled from the official Gson User Guide. Gson’s performance is competitive with other JSON frameworks, and being Google-maintained makes it a solid choice for Java/Android JSON processing.
Gson is a Java library developed by Google for serializing Java objects to JSON and deserializing JSON strings back to Java objects.
Performance and Scalability
Benchmark data from a desktop system (dual opteron, 8GB RAM, 64-bit Ubuntu), reproducible via PerformanceTest:
- Strings: Deserialization of 25MB+ strings works without issues
- Large collections: Serialization of 1.4M objects, deserialization of 87K objects
- Gson 1.4 increased array deserialization limits from 80KB to 11MB
Basic Usage
Primitives
| |
Object Examples
| |
Key Points
privatefields are recommended- No annotations needed — all fields in the class and its superclasses are included by default
transientfields are excluded automaticallynullhandling:- During serialization,
nullfields are omitted - During deserialization, missing keys result in
nullfield values
- During serialization,
syntheticfields are excluded- Inner, anonymous, and local class references to outer classes are ignored
Nested Classes
Gson can serialize/deserialize static nested classes easily, but cannot auto-deserialize non-static inner classes because their no-arg constructors need an outer class reference.
| |
Solutions:
- Define B as
static class B - Provide a custom InstanceCreator (works but not recommended)
Arrays
| |
Multi-dimensional arrays are also supported.
Collections
| |
Note: Java’s type erasure requires
TypeTokento specify generic types for deserialization.
Generics
Type erasure causes loss of generic type information:
| |
Use TypeToken:
| |
Mixed Type Collections
For ['hello', 5, {name: 'GREETINGS', source: 'guest'}]:
Three approaches:
- Recommended: Parse each element individually using
JsonParser - Register a type adapter for
Collection.class - Use
Collection<MyCollectionMemberType>with a registered adapter
Built-in Type Support
Gson provides built-in serializers/deserializers for java.net.URL, java.net.URI, plus Joda-Time types (DateTime, Instant) via custom converters.
Custom Serialization/Deserialization
| |
Pretty Printing
Default output is compact. For readable formatting:
| |
Null Object Support
By default, null fields are omitted. To include them:
| |
Versioning
Use @Since annotation for versioned field control:
| |
Field Exclusion
Built-in mechanisms:
- Modifier-based: Exclude
transientandstaticby default - @Expose annotation: Whitelist fields for serialization
- Custom ExclusionStrategy: Full programmatic control
Field Naming
Use @SerializedName for custom field names, or FieldNamingPolicy for global naming conventions.