A Java library for converting Java objects to JSON and vice versa, commonly used in Android development.
Quick Demo
Add implementation 'com.google.code.gson:gson:VERSION' to your app's build.gradle file.data class User(val name: String, val age: Int)val gson = Gson()
val json = gson.toJson(User("Alice", 30))val user = gson.fromJson(json, User::class.java)Show the JSON string or parsed object in a TextView or log output.
Quick Start
Setup Steps
- Add the Gson dependency to your app's build.gradle file.
- Create a Gson instance in your code.
- 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
Use Cases
When Not to Use
Usage Examples
Gson gson = new Gson();
String json = gson.toJson(myObject);Converts a Java object into a JSON string.
MyClass obj = gson.fromJson(jsonString, MyClass.class);Parses a JSON string back into a Java object.
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
- 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.