Gson in Java – A Complete Guide with Examples
What is Gson?
Gson (Google’s JSON library) is a powerful Java library developed by Google to serialize Java objects into JSON format and deserialize JSON back into Java objects. It is simple to use and provides flexibility in handling JSON data.
✅ Why Gson?
- Lightweight and easy to use
- Supports serialization and deserialization
- Handles complex objects and generic types
- No need for XML configuration
- Integrates well with Java applications
⚡How to Add Gson to Your Project?
If you are using Maven, add the following dependency to your pom.xml:
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.10.1</version>
</dependency>
For Gradle, add:
implementation 'com.google.code.gson:gson:2.10.1'
➤ Basic Example – Serialization and Deserialization
1️⃣ Java Object to JSON (Serialization)
import com.google.gson.Gson;
class Student {
private String name;
private int age;
private String course;
public Student(String name, int age, String course) {
this.name = name;
this.age = age;
this.course = course;
}
}
public class GsonSerializationExample {
public static void main(String[] args) {
Student student = new Student("Ashish", 22, "Computer Science");
Gson gson = new Gson();
// Convert Java object to JSON
String json = gson.toJson(student);
System.out.println("Serialized JSON: " + json);
}
}
Output:
{"name":"Ashish","age":22,"course":"Computer Science"}
2️⃣ JSON to Java Object (Deserialization)
import com.google.gson.Gson;
public class GsonDeserializationExample {
public static void main(String[] args) {
String json = "{\"name\":\"Bhasker\",\"age\":25,\"course\":\"Mathematics\"}";
Gson gson = new Gson();
// Convert JSON to Java object
Student student = gson.fromJson(json, Student.class);
System.out.println("Student Name: " + student.name);
System.out.println("Student Age: " + student.age);
System.out.println("Student Course: " + student.course);
}
}
✅ Working with Collections
Example: List of Objects
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.List;
public class GsonListExample {
public static void main(String[] args) {
String jsonArray = "[{\"name\":\"Alice\",\"age\":22,\"course\":\"CS\"}," +
"{\"name\":\"Bob\",\"age\":25,\"course\":\"Math\"}]";
Gson gson = new Gson();
Type studentListType = new TypeToken<List<Student>>() {}.getType();
List<Student> students = gson.fromJson(jsonArray, studentListType);
for (Student s : students) {
System.out.println(s.name + " - " + s.course);
}
}
}
✅ Custom Serialization and Deserialization
If you want to customize how a class is serialized/deserialized, implement JsonSerializer and JsonDeserializer.
import com.google.gson.*;
import java.lang.reflect.Type;
class CustomStudentSerializer implements JsonSerializer<Student> {
@Override
public JsonElement serialize(Student student, Type typeOfSrc, JsonSerializationContext context) {
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("studentName", student.name);
jsonObject.addProperty("studentAge", student.age);
return jsonObject;
}
}
And register it:
Gson gson = new GsonBuilder()
.registerTypeAdapter(Student.class, new CustomStudentSerializer())
.create();
✅ Advantages of Gson
- Simple API
- Good performance
- No need for annotations unless custom behavior is needed
- Handles nested objects and generics
- Handles null values gracefully
⚠️ Limitations of Gson
- No streaming API like Jackson (though it does support streaming but not optimized for large data)
- Does not support JAXB annotations
- Custom serialization logic requires additional code
🎯Conclusion
Gson is a great library for handling JSON in Java applications. It provides easy-to-use APIs for serialization and deserialization, with flexibility for custom logic when necessary. Perfect for small to medium-sized applications or when you need quick and efficient JSON handling.