Let's get started with a Microservice Architecture with Spring Cloud:
Deserialize to a Map with Correct Type for Each Value
Last updated: October 2, 2025
1. Introduction
Deserialization is the process of converting data from one format, like JSON, XML, or bytes, back into Java objects. When we deserialize to a Map<String, Object>, we want each value in the map to have its correct Java type – not just strings, but actual integers, booleans, arrays, and nested objects.
In this tutorial, we’ll learn how to properly deserialize data while preserving the original data types of each field using several different approaches.
2. Using Jackson Library
Jackson is the most widely used JSON processing library in Java. It provides fast and reliable deserialization with excellent type preservation.
To use Jackson, we first need to add the dependency to our pom.xml file:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.19.2</version>
</dependency>
Here’s how we can do it using Jackson:
public class JacksonDeserializer {
private final ObjectMapper objectMapper;
public JacksonDeserializer() {
this.objectMapper = new ObjectMapper();
}
public Map<String, Object> deserializeToMapUsingJackson(String jsonString) {
try {
TypeReference<Map<String, Object>> typeRef = new TypeReference<Map<String, Object>>() {};
Map<String, Object> result = objectMapper.readValue(jsonString, typeRef);
return result;
} catch (Exception e) {
throw new RuntimeException("Failed to deserialize JSON: " + e.getMessage(), e);
}
}
}
In this example, we first create an ObjectMapper to handle the JSON processing. Then we use a TypeReference<Map<String, Object>> to tell Jackson that we want to deserialize the JSON into a map with string keys and values of different types.
Let’s test our implementation with a sample JSON:
String json = """
{
"name": "John",
"age": 30,
"isActive": true,
"salary": 50000.75,
"hobbies": ["reading", "coding"],
"address": {
"street": "123 Main St",
"city": "New York"
}
}
""";
Map<String, Object> result = deserializeToMapUsingJackson(json);
assertEquals("John", result.get("name"));
assertEquals(30, result.get("age"));
assertEquals(true, result.get("isActive"));
assertEquals(50000.75, result.get("salary"));
assertTrue(result.get("hobbies") instanceof ArrayList);
This test confirms that each field in the JSON is deserialized into the correct Java type — String for the name, Integer for the age, Boolean for the isActive, Double for the salary, and ArrayList for the hobbies.
The main advantage of Jackson is that it is very fast and reliable, with excellent support for handling different types of JSON.
3. Using Gson Library
Gson is another popular JSON library for Java, created by Google. It is lightweight, easy to use, and works well for simple serialization and deserialization tasks.
To use Gson, we first need to add the dependency to our pom.xml file:
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.12.1</version>
</dependency>
Here’s an example of using Gson for deserialization:
public class GsonDeserializer {
private final Gson gson;
public GsonDeserializer() {
this.gson = new Gson();
}
public Map<String, Object> deserializeToMapUsingGson(String jsonString) {
try {
Type type = new TypeToken<Map<String, Object>>() {}.getType();
Map<String, Object> result = gson.fromJson(jsonString, type);
return result;
} catch (Exception e) {
throw new RuntimeException("Failed to deserialize JSON: " + e.getMessage(), e);
}
}
}
First, we initialize a Gson instance to handle JSON parsing. Using a TypeToken<Map<String, Object>>, we tell Gson to deserialize the JSON into a map where keys are strings and values can be of any type.
Let’s test our implementation with a sample JSON:
Map<String, Object> result = deserializer.deserializeToMapUsingGson(json);
assertEquals("John", result.get("name"));
assertEquals(30.0, result.get("age"));
assertEquals(true, result.get("isActive"));
assertEquals(50000.75, result.get("salary"));
assertTrue(result.get("hobbies") instanceof ArrayList);
This test shows that Gson successfully deserializes the JSON into a Map<String, Object>.
However, unlike Jackson, Gson treats all numbers as Double by default, so both age and salary are deserialized as Double. This is important to keep in mind if we need strict type handling.
The main advantage of Gson is that it is very simple and lightweight, making it easy to set up for small projects. The downside is that type preservation is weaker compared to Jackson, especially with numbers.
4. Using org.json Library
The org.json library is a lightweight and simple tool for working with JSON in Java. It is easy to use and works well for small or straightforward JSON parsing tasks.
To use org.json, we can add the Maven dependency:
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20250107</version>
</dependency>
With org.json, we can parse JSON into a map as follows:
public class OrgJsonDeserializer {
public Map<String, Object> deserializeToMapUsingOrgJson(String jsonString) {
try {
JSONObject jsonObject = new JSONObject(jsonString);
Map<String, Object> result = new HashMap<>();
for (String key : jsonObject.keySet()) {
Object value = jsonObject.get(key);
if (value instanceof JSONArray) {
value = ((JSONArray) value).toList();
} else if (value instanceof JSONObject) {
value = ((JSONObject) value).toMap();
}
result.put(key, value);
}
return result;
} catch (Exception e) {
throw new RuntimeException("Failed to deserialize JSON: " + e.getMessage(), e);
}
}
}
In this example, we create a JSONObject to parse the JSON string. We then iterate over its keys, converting each value. If the value is a JSONArray, we convert it to a List for easier handling in Java. This gives us a Map<String, Object> where each value can be a primitive type or a list.
Let’s test the implementation with a sample JSON:
Map<String, Object> result = deserializer.deserializeToMapUsingOrgJson(json);
assertEquals("John", result.get("name"));
assertEquals(30, result.get("age"));
assertEquals(true, result.get("isActive"));
assertEquals(BigDecimal.valueOf(50000.75), result.get("salary"));
assertTrue(result.get("hobbies") instanceof List);
assertTrue(result.get("address") instanceof Map);
This test shows that org.json successfully converts the JSON into a Map<String, Object>. Unlike Gson, numeric values are preserved as Integer and use BigDecimal for decimal numbers to maintain precision. This can make the type handling a bit simpler for mixed numbers.
However, org.json’s main limitation is that it doesn’t handle complex type mappings or nested objects as automatically as Jackson or Gson.
For small projects or quick parsing tasks, it’s a solid and lightweight choice.
5. Using JSON-P (Java JSON Processing API)
JSON-P (Java API for JSON Processing) is a standardized Java API for JSON processing. It allows manual parsing of JSON with full control over type conversion, which makes it very precise but slightly more verbose.
To use JSON-P, we need to add the dependency for both the API and an implementation to our pom.xml file:
<dependency>
<groupId>jakarta.json</groupId>
<artifactId>jakarta.json-api</artifactId>
<version>2.1.3</version>
</dependency>
<dependency>
<groupId>org.eclipse.parsson</groupId>
<artifactId>parsson</artifactId>
<version>1.1.5</version>
</dependency>
With JSON-P, we can parse JSON into a map while handling each value’s type explicitly:
public class JsonPDeserializer {
public Map<String, Object> deserializeToMapUsingJSONP(String jsonString) {
try (JsonReader reader = Json.createReader(new StringReader(jsonString))) {
JsonObject jsonObject = reader.readObject();
return convertJsonToMap(jsonObject);
} catch (Exception e) {
throw new RuntimeException("JSON-P parsing failed: " + e.getMessage(), e);
}
}
private Map<String, Object> convertJsonToMap(JsonObject jsonObject) {
Map<String, Object> result = new HashMap<>();
for (Map.Entry<String, JsonValue> entry : jsonObject.entrySet()) {
String key = entry.getKey();
JsonValue value = entry.getValue();
result.put(key, convertJsonValue(value));
}
return result;
}
private Object convertJsonValue(JsonValue jsonValue) {
switch (jsonValue.getValueType()) {
case STRING:
return ((JsonString) jsonValue).getString();
case NUMBER:
jakarta.json.JsonNumber num = (JsonNumber) jsonValue;
return num.isIntegral() ? num.longValue() : num.doubleValue();
case TRUE:
return true;
case FALSE:
return false;
case NULL:
return null;
case ARRAY:
return convertJsonArray((JsonArray) jsonValue);
case OBJECT:
return convertJsonToMap((JsonObject) jsonValue);
default:
return jsonValue.toString();
}
}
private List<Object> convertJsonArray(JsonArray jsonArray) {
List<Object> list = new ArrayList<>();
for (JsonValue value : jsonArray) {
list.add(convertJsonValue(value));
}
return list;
}
}
In this example, we use a JsonReader to parse the JSON string into a JsonObject. We then manually convert each value using convertJsonValue(), which handles strings, numbers, booleans, arrays, nested objects, and nulls explicitly.
Arrays are converted into List<Object> for easier handling in Java. This approach gives full control over how each JSON value is converted into the corresponding Java type.
We can verify the implementation with a sample JSON:
Map<String, Object> result = deserializeToMapUsingJSONP(json);
assertEquals("John", result.get("name"));
assertEquals(30.0, result.get("age"));
assertEquals(true, result.get("isActive"));
assertEquals(50000.75, result.get("salary"));
assertTrue(result.get("hobbies") instanceof List);
assertTrue(result.get("address") instanceof Map);
JSON-P parses numbers carefully; integers and decimals are converted to Double, ensuring precise type handling.
The main advantage of using JSON-P is that it gives precise control over type conversion, making it ideal when exact handling of numbers, booleans, and nested structures is required. The trade-off is that the code is more verbose, and we must manually handle all JSON types.
6. Summary
Here’s a summary table comparing Jackson, Gson, org.json, and JSON-P:
| Library | Dependency | Type Handling | Use Case |
|---|---|---|---|
| Jackson | Yes | Excellent type preservation (Integer, Long, Double, Boolean, List, nested objects) | Production apps, complex JSON structures, performance-critical projects |
| Gson | Yes | Numbers default to Double; handles Boolean, String, List, and nested objects | Simple projects, lightweight JSON parsing, quick setup |
| org.json | Yes (or sometimes included) | Integer and Double preserved; Boolean, String, JSONArray converted to List | Small projects, simple JSON parsing, minimal dependencies |
| JSON-P | No, part of the Java standard | Numbers default to Double; handles Boolean, String, List, nested objects, and nulls explicitly | When precise type control is needed, strict parsing and standard Java projects are required. |
7. Conclusion
In this article, we’ve explored multiple ways to deserialize JSON data into Map<String, Object> while preserving the correct data types. Jackson provides the most comprehensive solution for complex JSON, whereas Gson, org.json, and JSON-P offer lighter or more controlled alternatives depending on our project requirements.
The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.















