Language: Java
Web
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.
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.
Add com.google.code.gson:gson dependency in pom.xmlAdd implementation 'com.google.code.gson:gson:2.10.1' in build.gradleGson 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.
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; }
}Converts a Java object `User` into a JSON string using Gson.
String json = "{\"id\":1,\"name\":\"Alice\"}";
User user = gson.fromJson(json, User.class);
System.out.println(user.name);Converts a JSON string into a Java `User` object using Gson.
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());Demonstrates serialization and deserialization of lists of Java objects using `TypeToken`.
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
}
}Shows how to customize serialization by implementing `JsonSerializer`.
import com.google.gson.annotations.Expose;
class User {
@Expose private int id;
@Expose private String name;
private String password;
}Only fields annotated with `@Expose` will be serialized when using `GsonBuilder().excludeFieldsWithoutExposeAnnotation()`.
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String prettyJson = gson.toJson(user);
System.out.println(prettyJson);Formats JSON output for readability.
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.