#1 India's Top IT Training Institute
×

About Uncodemy

Know more about who we are and what we stand for.

About Us

About Us

Discover our mission to equip individuals with essential IT skills and industry expertise.

Read More →
UnCodeMy Gallery

UnCodeMy Gallery

Explore highlights from our IT training sessions and success stories.

Read More →
Mentors

Mentors

Meet the industry experts who train and guide you through your course.

Read More →
Free Resources

Free Resources

Free tutorials, interview questions, tools and calculators to help you learn.

Explore →
×

Free Resources

Learn, practice and plan your career — bilkul free.

Tutorials

Tutorials

Step-by-step written tutorials to learn any technology at your own pace.

Read More →
Free Counselling

Free Counselling

Book a free video counselling session and pick the right course for you.

Read More →
Online Compiler

Online Compiler

Write, run and test your code online — no setup required.

Read More →
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.

Using a Map in an API Test

A typical place for this conversion is checking an API response without building a Java class for it. The response body arrives as a string, gets turned into a Map, and individual fields are asserted:

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;

String body = "{\"id\":101,\"name\":\"Asha\",\"active\":true,"
            + "\"address\":{\"city\":\"Pune\"},\"roles\":[\"admin\",\"qa\"]}";

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

Map<String, Object> address = (Map<String, Object>) user.get("address");
List<Object> roles = (List<Object>) user.get("roles");

assert "Asha".equals(user.get("name"));
assert "Pune".equals(address.get("city"));
assert roles.contains("qa");

Nested JSON objects come back as maps (Gson uses its own LinkedTreeMap class, which keeps key order) and JSON arrays come back as ArrayList. Booleans become Boolean and strings become String.

The Number Surprise: 101 Becomes 101.0

When the target type is Object, Gson reads every JSON number as a Double by default. So user.get("id") returns 101.0, and a check like user.get("id").equals(101) fails because a Double is being compared with an Integer.

There are two clean fixes. Compare numerically, for example ((Number) user.get("id")).intValue() == 101, or tell Gson how to read numbers when you build it:

import com.google.gson.GsonBuilder;
import com.google.gson.ToNumberPolicy;

Gson gson = new GsonBuilder()
        .setObjectToNumberStrategy(ToNumberPolicy.LONG_OR_DOUBLE)
        .create();
// now 101 is read as a Long and 99.5 as a Double

This option is available in newer Gson releases. If your project uses an old version, the numeric comparison approach works everywhere.

Controlling the JSON Gson Produces

When building a request body from a Map, two builder settings are worth knowing:

  • serializeNulls(): Gson skips keys whose value is null unless you enable this. Some APIs treat a missing key differently from a key set to null, so choose deliberately.
  • setPrettyPrinting(): formats output across lines with indentation, which makes test logs and failure reports much easier to read.
Gson gson = new GsonBuilder().serializeNulls().setPrettyPrinting().create();
Map<String, Object> payload = new LinkedHashMap<>();
payload.put("name", "Asha");
payload.put("manager", null);
System.out.println(gson.toJson(payload));

Using LinkedHashMap keeps keys in insertion order, while a plain HashMap may print them in any order.

Map or POJO: Choosing Well

  • Use a Map for quick checks, dynamic keys, or responses whose shape varies.
  • Use a Java class (POJO) when the structure is stable and many tests read it, since typos in field names then become compile errors instead of silent nulls.
  • For API tests that already use REST Assured, response.jsonPath().getMap("$") gives a similar Map without a separate parsing step, but Gson remains handy for building request bodies and comparing stored JSON files.
  • When comparing a whole response against an expected JSON file, convert both to Maps and compare them with equals(). Key order then no longer matters, which avoids false failures caused only by formatting.
  • Avoid long chains of casts like ((Map) ((Map) a.get("x")).get("y")); if you need deep access often, a POJO or Gson's JsonObject API is cleaner.

Ready to master real-world software testing?

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

Explore Course