Recommended Free Tools
Gson maps Java objects to JSON and JSON back to Java objects. For ordinary classes, create a Gson instance and use toJson and fromJson; for generic targets such as List<Person>, preserve the element type with TypeToken. This guide builds from a simple model to collections, maps, custom adapters, and common pitfalls.
Add Gson and define a Java model
The official Gson User Guide lists com.google.code.gson:gson:2.14.0 in its Maven and Gradle examples. That version is the one shown in the moving main-branch guide; check the project’s current release information when selecting a dependency version.
A model can be a plain Java class whose fields correspond to the JSON shape. Gson includes fields by default, including private fields:
public class Person {
private String name;
private int age;
public Person() {
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() { return name; }
public int getAge() { return age; }
}
Treat field names as part of the external JSON contract. When JSON uses a different name, use Gson’s naming annotations or configure a naming strategy rather than relying on accidental Java naming choices. See the Gson User Guide for dependency examples and field-naming options.
How do I convert a Java object to JSON with Gson?
Call toJson on a Gson instance. For example:
import com.google.gson.Gson;
Person person = new Person("Ada", 37);
Gson gson = new Gson();
String json = gson.toJson(person);
System.out.println(json);
The result is a JSON string representing the object’s fields. Gson can also work with existing Java objects whose source code you do not own, though inaccessible types or unsuitable field layouts may call for a custom adapter.
How do I convert JSON to a Java object in Gson?
Pass the JSON and target class to fromJson when the target is a non-generic class:
String json = "{"name":"Ada","age":37}";
Person copy = gson.fromJson(json, Person.class);
For repeated work, reuse a configured Gson instance rather than creating one for every conversion. Gson documents instances as thread-safe and reusable across multiple threads; configuration is applied when the instance is built.
Rank #2
Deserialization creates an object representation; it does not validate application rules. Check required values, ranges, and cross-field constraints in application code after parsing, and handle malformed or incompatible JSON appropriately.
How do I deserialize a list with Gson?
A raw List.class does not retain the element type. Java erases generic parameters at runtime, so Gson cannot infer that the list should contain Person objects from that class alone. Use a parameterized TypeToken:
import com.google.gson.reflect.TypeToken;
import java.util.List;
TypeToken<List<Person>> peopleType = new TypeToken<List<Person>>() {};
List<Person> people = gson.fromJson(json, peopleType);
Current Gson documentation shows the token overload; older versions may require passing peopleType.getType() to fromJson. Use the overload available in the version your project depends on.
How do I use Gson with generic types?
Preserve the complete parameterized target, not merely its raw class. For a wrapper such as Envelope<Person>, passing Envelope.class loses the type argument in the same way a raw list does. Capture the full type:
TypeToken<Envelope<Person>> envelopeType =
new TypeToken<Envelope<Person>>() {};
Envelope<Person> envelope = gson.fromJson(json, envelopeType);
If a TypeToken fails or resolves unexpectedly, verify that it contains a concrete type argument rather than a type variable that is unavailable at runtime. On Android, also check whether code shrinking removed generic signature metadata.
Free tools Windows power users keep installed
One-click scans. No signup required.
How Gson represents maps
By default, Gson writes a map as a JSON object and converts map keys to strings. That is straightforward for string-like keys, but relying on an arbitrary key object’s toString() can produce keys that are ambiguous or cannot be reconstructed reliably.
Rank #4
For complex map keys, configure enableComplexMapKeySerialization() on a builder. If the key adapter produces structured JSON, Gson may encode the map as an array of key-value pairs instead of a JSON object. Choose the representation with the receiving system’s expected format in mind.
Gson gson = new GsonBuilder()
.enableComplexMapKeySerialization()
.create();
How do I write a custom Gson TypeAdapter?
When the default field-based representation is unsuitable, a custom adapter lets the application define how a type is read and written. Register an adapter with GsonBuilder.registerTypeAdapter, then use the resulting configured Gson instance for conversions:
Gson gson = new GsonBuilder()
.registerTypeAdapter(MyType.class, new MyTypeAdapter())
.create();
A TypeAdapter gives direct control over streaming JSON reads and writes. Tree-based JsonSerializer and JsonDeserializer interfaces can be simpler for transformations that are naturally expressed as a JSON tree, but the Gson API documentation describes them as less efficient than TypeAdapter in some cases.
Do these 3 things before closing this tab:
1Scan for outdated or missing drivers - takes under a minute2Clear out junk files and repair common Windows errors3Fix the driver behind crashes, sound loss and screen glitchesBest Value
Registration is ordinarily scoped to the exact type. If the value is a subclass or a parameterized variant, a registration for a different type may not apply; consider a hierarchy adapter or a carefully designed adapter factory where appropriate. Confirm both that the adapter targets the actual runtime/declared type involved and that the code path uses the configured Gson instance, not a separately constructed default instance.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Defaults, compatibility, and safe handling
Reflection and inaccessible fields
Some platform or library types are not suitable for Gson’s reflective defaults. The troubleshooting guide recommends writing an adapter or changing the data type. Exclude a field only when it genuinely should not be serialized or deserialized; exclusion is not a general fix for an inaccessible field that the JSON contract needs.
Android shrinking
Code shrinking can remove generic signatures or constructors that reflective deserialization needs. Consult current Gson and R8 documentation, and preserve required metadata and constructors in the application’s shrinker configuration. Gson’s troubleshooting guide says versions 2.11.0 and newer specify default R8 configuration, but actual behavior still depends on the current toolchain and project rules.
Records and Java versions
The Gson changelog records Java record serialization and deserialization support beginning with Gson 2.10 when running on Java 16 or later. The changelog itself directs readers to GitHub Releases for changes newer than 2.10, so it should not be treated as a complete current compatibility matrix.
Quick wins for a faster PC:
Scan for outdated or missing drivers - takes under a minuteDriver Scan →Clear out junk files and repair common Windows errorsFree Scan →Do not instantiate arbitrary classes from untrusted JSON
Do not let untrusted input choose an arbitrary Java class to instantiate. Gson intentionally prohibits serializing and deserializing java.lang.Class for security reasons. If a payload needs to identify one of several supported types, map a constrained alias to a known type or use a custom adapter limited to a known base type; never treat arbitrary class names from input as permission to construct those classes. See the Gson Troubleshooting Guide for the documented security and adapter guidance.
Quick Recap
Quick choice guide
| Need | Use | Why |
|---|---|---|
| Convert an ordinary model | toJson(object) and fromJson(json, Model.class) |
A concrete class supplies the target type. |
| Read a parameterized collection or wrapper | TypeToken<...> |
Retains generic type information erased from raw classes. |
| Represent complex map keys | enableComplexMapKeySerialization() |
Allows structured key serialization and can yield key-value pair arrays. |
| Override a type’s JSON format | TypeAdapter or tree serializer/deserializer |
Provides explicit control where reflective defaults are unsuitable. |
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

