Serializing & Deserializing Json Using Gson
Serialization (Object → JSON)
Gson gson = new Gson();
User user = new User("Asha", 28);
String json = gson.toJson(user);
// {"name":"Asha","age":28}
Deserialization (JSON → Object)
String json = "{\"name\":\"Asha\",\"age\":28}";
User user = gson.fromJson(json, User.class);
System.out.println(user.name); // Asha
Why This Matters for Testing
Serialization builds request bodies without manual string concatenation, and deserialization turns a response directly into an object whose fields can be asserted on with normal Java code.
Adding Gson and Preparing a POJO
Gson is a Java library from Google that converts Java objects to JSON and back. In a Maven project, add the com.google.code.gson:gson dependency to your pom.xml, choosing the current stable version from Maven Central.
Gson maps JSON keys to Java fields by name. A simple class for the earlier example looks like this:
public class User {
String name;
int age;
public User() { } // handy for deserialization
public User(String name, int age) {
this.name = name;
this.age = age;
}
}
If the JSON key differs from the field name, use the @SerializedName annotation so the Java code can follow normal naming rules:
import com.google.gson.annotations.SerializedName;
public class Employee {
@SerializedName("first_name")
String firstName;
@SerializedName("job_title")
String jobTitle;
}
Worked Example: Using Gson in an API Test
Here is how the two directions fit together in a Rest Assured test. The request body is built from an object, and the response is turned back into an object for assertions.
Gson gson = new Gson();
Employee input = new Employee();
input.firstName = "Ravi";
input.jobTitle = "QA Lead";
String body = gson.toJson(input);
String responseJson =
given()
.contentType("application/json")
.body(body)
.when()
.post("https://example.com/api/employees")
.then()
.statusCode(201)
.extract().asString();
Employee created = gson.fromJson(responseJson, Employee.class);
Assert.assertEquals(created.jobTitle, "QA Lead");
The URL is a placeholder; point it at the API you are testing. The big advantage of this style is maintenance. If the API adds a new field, you add one line to the class instead of hunting through hand-written JSON strings in dozens of tests, and the compiler warns you about typos in field names that a raw string would hide.
Handling Lists, Nested Objects and Pretty Output
Nested JSON objects map naturally to nested classes: a User with an Address field will read a nested "address": {...} block automatically.
Lists need extra help, because Java's generics are erased at runtime. Use TypeToken to tell Gson the full type:
Type listType = new TypeToken<List<User>>(){}.getType();
List<User> users = gson.fromJson(jsonArray, listType);
For readable logs or test reports, build Gson with pretty printing:
Gson pretty = new GsonBuilder().setPrettyPrinting().create();
System.out.println(pretty.toJson(user));
Gson Pitfalls Testers Run Into
- Null fields disappear. By default Gson skips null values when serializing. If the API expects an explicit
null, usenew GsonBuilder().serializeNulls().create(). - Missing keys do not fail. If the response lacks a field, Gson simply leaves it as null or zero. Assert important fields explicitly rather than assuming they were filled.
- Type mismatches. A JSON string like
"28"mapped to anintmay convert, but unexpected formats can throwJsonSyntaxException. Treat that as a test failure worth reporting. - Dates. Configure a date format with
GsonBuilderinstead of relying on defaults.
When to choose something else: Jackson is the other common choice and is used by default in many frameworks. Both work well; pick the one your project already uses so you do not mix mapping rules.
Ready to master real-world software testing?
Learn manual and automation testing hands-on with mentor-led sessions.