Google Gson: The Simple, Zero-Dependency Library
While Jackson is powerful, Gson is simple. No modules, no chaos. Just new Gson(). Perfect for Android and minimalists.
The Simple Logic
Gson shines because it doesn't need to be "Configured". It works out of the box for 90% of use cases.
Gson gson = new Gson();
// One line. Done.
User user = gson.fromJson(jsonString, User.class);
Controlling Null Fields
The Gotcha: Gson does NOT write null values to JSON by default. If user.name is null, the field "name" simply vanishes from the output.
To fix this, you cannot use new Gson(). You must use the Builder:
Gson gson = new GsonBuilder()
.serializeNulls()
.create();
Powerful API Versioning
Gson has a unique feature that Jackson lacks: built-in versioning annotations. This allows you to manage multiple API versions with a single POJO.
public class User {
@Since(1.0) String name;
@Since(2.0) String email;
@Until(1.5) String legacyField;
}
// Usage
Gson v1 = new GsonBuilder().setVersion(1.0).create();
Handling Lists & Generics
Java deletes generic type info at compile time (Type Erasure). To convert a List<User>, you must capture the type definition using a TypeToken.
Type listType = new TypeToken<List<User>>(){}.getType();
List<User> users = gson.fromJson(jsonArray, listType);
Handling Snake_Case
Don't pollute your code with thousands of @SerializedName annotations. Use a global policy to automatically map API defaults (snake_case) to Java (camelCase).
Gson gson = new GsonBuilder()
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
.create();
Android Performance: TypeAdapters
Reflection is slow on Android. For maximum performance, or to parse massive files without crashing memory, use a streaming TypeAdapter.
public class UserAdapter extends TypeAdapter<User> {
@Override
public User read(JsonReader in) throws IOException {
in.beginObject();
while(in.hasNext()) {
// Read tokens manually... extremely fast!
}
in.endObject();
}
}
The "Inner Class" Crash
Problem: Standard inner classes in Java hold a reference to their parent. Gson cannot instantiate them, leading to InstantiationException.
Common Questions
How do I convert a List?
Use TypeToken. See the "Handling Lists" section above for the exact code snippet.
What handles Enum conversion?
Gson automatically converts JSON strings to Enums if they match the Enum name exactly. Use @SerializedName on Enum constants if they differ.
Jackson vs. Gson
| Feature | Gson | Jackson |
|---|---|---|
| Dependencies | Zero (Single Jar) | Multiple Modules |
| Null Handling | Manual Config | Standard |
Generate Gson Code Instantly
Forget manually writing @SerializedName. Our tool generates perfect, clean Gson code in seconds.