Back to Course
Gson & JSON

Converting Json To Map and Vice Versa Using Gson

JSON to Map

Gson gson = new Gson();
Type type = new TypeToken<Map<String, Object>>(){}.getType();
Map<String, Object> map = gson.fromJson(jsonString, type);

Map to JSON

Map<String, Object> data = new HashMap<>();
data.put("name", "Asha");
data.put("age", 28);
String json = gson.toJson(data);

Why Use a Map Instead of a Class?

Converting to a Map is useful when the JSON structure is dynamic or unknown ahead of time, letting a test inspect keys and values generically without needing a matching Java class.

Ready to master real-world software testing?

Learn manual and automation testing hands-on with mentor-led sessions.

Explore Course