eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Partner – LambdaTest – NPI EA (cat=Testing)
announcement - icon

Regression testing is an important step in the release process, to ensure that new code doesn't break the existing functionality. As the codebase evolves, we want to run these tests frequently to help catch any issues early on.

The best way to ensure these tests run frequently on an automated basis is, of course, to include them in the CI/CD pipeline. This way, the regression tests will execute automatically whenever we commit code to the repository.

In this tutorial, we'll see how to create regression tests using Selenium, and then include them in our pipeline using GitHub Actions:, to be run on the LambdaTest cloud grid:

>> How to Run Selenium Regression Tests With GitHub Actions

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

eBook – Jackson – NPI (cat=Jackson)
announcement - icon

Jackson and JSON in Java, finally learn with a coding-first approach:

>> Download the eBook

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.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

eBook Jackson – NPI EA – 3 (cat = Jackson)
eBook Jackson – NPI (cat = Jackson)