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.

Course – Summer Sale 2026 – NPI EA (cat= Baeldung)
announcement - icon

Yes, we're now running our only Summer Sale. All Courses are 30% off until 20th July, 2026:

>> EXPLORE ACCESS NOW

Course – Summer Sale 2026 – NPI (cat=Baeldung)
announcement - icon

Yes, we're now running our only Summer Sale. All Courses are 30% off until 20th July, 2026:

>> EXPLORE ACCESS NOW

1. Overview

In this tutorial, we’ll look at different ways to read JSON documents as Maps and compare them. We’ll also look at ways to find the differences between the two Maps.

2. Converting to Map

First, we’ll look at different ways to convert JSON documents to Maps. Let’s look at the JSON objects we’ll use for our test.

Let’s create a file named first.json with the following content:

{
  "name": "John",
  "age": 30,
  "cars": [
    "Ford",
    "BMW"
  ],
  "address": {
    "street": "Second Street",
    "city": "New York"
  },
  "children": [
    {
      "name": "Sara",
      "age": 5
    },
    {
      "name": "Alex",
      "age": 3
    }
  ]
}

Similarly, let’s create another file named second.json with the following content:

{
  "name": "John",
  "age": 30,
  "cars": [
    "Ford",
    "Audi"
  ],
  "address": {
    "street": "Main Street",
    "city": "New York"
  },
  "children": [
    {
      "name": "Peter",
      "age": 5
    },
    {
      "name": "Cathy",
      "age": 10
    }
  ]
}

As we can see, there are two differences between the above JSON documents:

  • The value of the cars array is different
  • The value of the street key in the address object is different
  • The children arrays have multiple differences

2.1. Using Jackson

Jackson is a popular library used for JSON operations. We can use Jackson to convert a JSON to a Map.

Let’s start by adding the Jackson dependency:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.15.2</version>
</dependency>

Now we can convert a JSON document to Map using Jackson:

class JsonUtils {
    public static Map<String, Object> jsonFileToMap(String path) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        return mapper.readValue(new File(path), new TypeReference<Map<String, Object>>() {});
    }
}

Here, we’re using the readValue() method from the ObjectMapper class to convert the JSON document to a Map. It takes the JSON document as a File object and a TypeReference object as parameters.

2.2. Using Gson

Similarly, we can also use Gson to convert the JSON document to a Map. We need to include the dependency for this:

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.11.0</version>
</dependency>

Now let’s look at the code to convert the JSON:

public static Map<String, Object> jsonFileToMapGson(String path) throws IOException {
    Gson gson = new Gson();
    return gson.fromJson(new FileReader(path), new TypeToken<Map<String, Object>>() {}.getType());
}

Here, we’re using the fromJson() method from the Gson class to convert the JSON document to a Map. It takes the JSON document as a FileReader object and a TypeToken object as parameters.

3. Comparing Maps

Now that we’ve converted the JSON documents to Maps, let’s look at different ways to compare them.

3.1. Using Guava’s Map.difference()

Guava provides a Maps.difference() method that can be used to compare two Maps. To utilize this, let’s add the Guava dependency to our project:

<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>33.2.1-jre</version>
</dependency>

Now, let’s look at the code to compare the Maps:

@Test
void givenTwoJsonFiles_whenCompared_thenTheyAreDifferent() throws IOException {
    Map<String, Object> firstMap = JsonUtils.jsonFileToMap("src/test/resources/first.json");
    Map<String, Object> secondMap = JsonUtils.jsonFileToMap("src/test/resources/second.json");

    MapDifference<String, Object> difference = Maps.difference(firstFlatMap, secondFlatMap);
    difference.entriesDiffering().forEach((key, value) -> {
        System.out.println(key + ": " + value.leftValue() + " - " + value.rightValue());
    });
    assertThat(difference.areEqual()).isFalse();
}

Guava can only compare one level of Maps. This doesn’t work for our case as we have a nested Map.

Let’s look at how we compare our nested Maps above. We’re using the entriesDiffering() method to get the differences between the Maps. This returns a Map of differences where the key is the path to the value, and the value is a MapDifference.ValueDifference object. This object contains the values from both the Maps. If we run the test, we’ll see the keys that are different between the Maps and their values:

cars: [Ford, BMW] - [Ford, Audi]
address: {street=Second Street, city=New York} - {street=Main Street, city=New York}
children: [{name=Sara, age=5}, {name=Alex, age=3}] - [{name=Peter, age=5}, {name=Cathy, age=10}]

As we can see, this shows that the cars, address, and children fields are different, and the differences are listed. However, this doesn’t show which nested fields are leading to these differences. For example, it doesn’t point out that the street field in the address objects is different.

3.2. Flattening Maps

To precisely point out differences between nested Maps, we’ll flatten the Maps so each key is a path to the value. For example, the street key in the address object will be flattened to address.street and so on.

Let’s look at the code for this:

class FlattenUtils {
    public static Map<String, Object> flatten(Map<String, Object> map) {
        return flatten(map, null);
    }

    private static Map<String, Object> flatten(Map<String, Object> map, String prefix) {
        Map<String, Object> flatMap = new HashMap<>();
        map.forEach((key, value) -> {
            String newKey = prefix != null ? prefix + "." + key : key;
            if (value instanceof Map) {
                flatMap.putAll(flatten((Map<String, Object>) value, newKey));
            } else if (value instanceof List) {
                // check for list of primitives
                Object element = ((List<?>) value).get(0);
                if (element instanceof String || element instanceof Number || element instanceof Boolean) {
                    flatMap.put(newKey, value);
                } else {
                    // check for list of objects
                    List<Map<String, Object>> list = (List<Map<String, Object>>) value;
                    for (int i = 0; i < list.size(); i++) {
                        flatMap.putAll(flatten(list.get(i), newKey + "[" + i + "]"));
                    }
                }
            } else {
                flatMap.put(newKey, value);
            }
        });
        return flatMap;
    }
}

Here, we’re using recursion to flatten the Map. For any field, one of the following conditions will be true:

  • The value could be a Map (nested JSON object). In this case, we’ll recursively call the flatten() method with the value as the parameter. For example, the address object will be flattened to address.street and address.city.
  • Next, we can check if the value is a List (JSON array). If the list contains primitive values, we’ll add the key and value to the flattened Map.
  • If the list contains objects, we’ll recursively call the flatten() method with each object as the parameter. For example, the children array will be flattened to children[0].namechildren[0].agechildren[1].name, and children[1].age.
  • If the value is neither a Map nor a List, we’ll add the key and value to the flattened Map.

This will be recursive until we reach the last level of the Map. At this point, we’ll have a flattened Map with each key as a path to the value.

3.3. Testing

Now that we’ve flattened the Maps, let’s look at how we can compare them using Maps.difference():

@Test
void givenTwoJsonFiles_whenCompared_thenTheyAreDifferent() throws IOException {
    Map<String, Object> firstFlatMap = FlattenUtils.flatten(JsonUtils.jsonFileToMap("src/test/resources/first.json"));
    Map<String, Object> secondFlatMap = FlattenUtils.flatten(JsonUtils.jsonFileToMap("src/test/resources/second.json"));

    MapDifference<String, Object> difference = Maps.difference(firstFlatMap, secondFlatMap);
    difference.entriesDiffering().forEach((key, value) -> {
        System.out.println(key + ": " + value.leftValue() + " - " + value.rightValue());
    });
    assertThat(difference.areEqual()).isFalse();
}

Again, we’ll print the keys and values that are different. This leads to the output below:

cars: [Ford, BMW] - [Ford, Audi]
children[1].age: 3 - 10
children[1].name: Alex - Cathy
address.street: Second Street - Main Street
children[0].name: Sara - Peter

4. Conclusion

In this article, we looked at comparing two JSON documents in Java. We looked at different ways to convert the JSON documents to Maps and then compared them using Guava’s Maps.difference() method. We also looked at how we can flatten the Maps so that we can compare nested Maps.

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.

Course – Summer Sale 2026 – NPI EA (cat= Baeldung)
announcement - icon

Yes, we're now running our only Summer Sale. All Courses are 30% off until 20th July, 2026:

>> EXPLORE ACCESS NOW

Course – Summer Sale 2026 – NPI (All)
announcement - icon

Yes, we're now running our only Summer Sale. All Courses are 30% off until 20th July, 2026:

>> EXPLORE ACCESS NOW

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