A Java library for converting Java objects to JSON and vice versa, commonly used in Android development.

Apache-2.0

Quick Demo

1Add Dependencyterminal
Add implementation 'com.google.code.gson:gson:VERSION' to your app's build.gradle file.
2Define Data Classcode
data class User(val name: String, val age: Int)
3Serialize to JSONcode
val gson = Gson()
val json = gson.toJson(User("Alice", 30))
4Deserialize from JSONcode
val user = gson.fromJson(json, User::class.java)
5Display in UIphone

Show the JSON string or parsed object in a TextView or log output.

Quick Start

Setup Steps

  1. Add the Gson dependency to your app's build.gradle file.
  2. Create a Gson instance in your code.
  3. Use the Gson instance to serialize or deserialize objects as needed.

Overview

Gson is a Java library developed by Google that allows easy conversion between Java objects and JSON format. It is widely adopted in Android applications for handling data serialization and deserialization, especially when working with REST APIs or local storage.

Features

Simple and intuitive API
Supports complex object graphs with nested classes
Custom serializers and deserializers via TypeAdapters
Efficient performance with minimal overhead
No annotations required for basic usage

Use Cases

Parsing JSON responses from network APIs
Saving Java objects to SharedPreferences in JSON format
Caching data structures as JSON strings for persistence

When Not to Use

When using Kotlin data classes with strict null-safety (consider Moshi for better Kotlin integration)
For streaming large JSON datasets (use libraries like Jackson streaming API)
In performance-critical scenarios where code generation is preferred

Usage Examples

Serialize Object to JSON
Gson gson = new Gson();
String json = gson.toJson(myObject);

Converts a Java object into a JSON string.

Deserialize JSON to Object
MyClass obj = gson.fromJson(jsonString, MyClass.class);

Parses a JSON string back into a Java object.

Custom TypeAdapter for Dates
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();

Configures Gson to use a specific date format during serialization.

Common Pitfalls

  • Default serialization can expose private fields if not configured properly
  • Handling of date formats may require custom adapters to avoid issues
  • Circular references in object graphs can lead to StackOverflowError without custom handling

Integration

Works well with

Retrofit for network request/response parsingRoom for converting database entities to JSONOkHttp for intercepting and modifying JSON payloads
  • Set ProGuard rules to prevent obfuscation from breaking serialization.

Alternatives

Moshi

Kotlin-first design with better null safety and support for Kotlin features.

Jackson

More extensive features and flexibility, but has a larger footprint and steeper learning curve.

FAQ

Is Gson thread-safe?

Yes, Gson instances are thread-safe once created and configured.

How do I handle custom date formats in Gson?

Use GsonBuilder to register a custom TypeAdapter or set a date format pattern.

Can Gson work with Kotlin data classes?

Yes, but for optimal Kotlin support, consider Moshi, which is designed with Kotlin in mind.

What ProGuard rules are needed for Gson?

Add rules to keep Gson classes and signatures, e.g., -keep class com.google.gson.** { *; } and -keepattributes Signature.

Does Gson support Androidx or Jetpack libraries?

Gson is a standalone Java library and works independently of Androidx, but can be used alongside them.

Maintenance & Health

  • The latest version and Maven coordinates are not specified; check the repository for current details.
  • Gson is actively maintained by Google, but updates may be infrequent.

Related libraries