What it is
Gson is a Java library by Google for converting Java objects to JSON and vice versa. It supports serialization and deserialization of Java objects, including collections, generics, and nested objects.
Gson allows developers to serialize Java objects into JSON strings and deserialize JSON strings into Java objects. It supports custom serializers, deserializers, and works well with collections and complex object hierarchies.
Installation
Add com.google.code.gson:gson dependency in pom.xmlGetting started
The smallest useful thing you can do with it, and what each part means.
import com.google.gson.Gson;
public class Main {
public static void main(String[] args) {
Gson gson = new Gson();
User user = new User(1, "Alice");
String json = gson.toJson(user);
System.out.println(json);
}
}
class User {
int id;
String name;
User(int id, String name) { this.id = id; this.name = name; }
}String json = "{\"id\":1,\"name\":\"Alice\"}";
User user = gson.fromJson(json, User.class);
System.out.println(user.name);Advanced usage
Where the library earns its place over a simpler alternative.
List<User> users = Arrays.asList(new User(1,"Alice"), new User(2,"Bob"));
String json = gson.toJson(users);
List<User> deserialized = gson.fromJson(json, new TypeToken<List<User>>(){}.getType());import com.google.gson.JsonElement;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import java.lang.reflect.Type;
class UserSerializer implements JsonSerializer<User> {
public JsonElement serialize(User user, Type typeOfSrc, JsonSerializationContext context) {
return context.serialize(user.name); // only serialize the name field
}
}import com.google.gson.annotations.Expose;
class User {
@Expose private int id;
@Expose private String name;
private String password;
}Gson gson = new GsonBuilder().setPrettyPrinting().create();
String prettyJson = gson.toJson(user);
System.out.println(prettyJson);Errors and fixes
The failures you are most likely to hit, and what actually resolves them.
- JsonSyntaxException
- Occurs when the JSON is malformed or doesn't match the Java object structure. Validate JSON input.
- JsonIOException
- Occurs during I/O operations. Handle stream/file errors when reading or writing JSON.
- JsonParseException
- Occurs when parsing fails. Ensure JSON format is correct and compatible with the target class.
Best practices
- Use `Gson` as a singleton to improve performance.
- Use `TypeToken` when deserializing generic types like collections.
- Leverage `@Expose` and `GsonBuilder` for field-level control.
- Handle null values explicitly with `serializeNulls()` if needed.
- Prefer Gson for simple JSON processing; use Jackson for complex or high-performance scenarios.
Background
Why it exists, and what it was reacting to.
Gson was created by Google to provide a simple and efficient way to handle JSON in Java applications. It emphasizes ease-of-use, flexibility, and compatibility with standard Java types, making it popular for REST APIs and configuration handling.
