Jackson Json parser has a nice feature that it can parse a Json String into a Map. You can then query the entries or simply ask on equality:

import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.*;

public class Test
{
    public static void main(String... args)
    {
        String input1 = "{\"state\":1,\"cmd\":1}";
        String input2 = "{\"cmd\":1,\"state\":1}";
        ObjectMapper om = new ObjectMapper();
        try {
            Map<String, Object> m1 = (Map<String, Object>)(om.readValue(input1, Map.class));
            Map<String, Object> m2 = (Map<String, Object>)(om.readValue(input2, Map.class));
            System.out.println(m1);
            System.out.println(m2);
            System.out.println(m1.equals(m2));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

The output is

{state=1, cmd=1}
{cmd=1, state=1}
true
Answer from Sharon Ben Asher on Stack Overflow
🌐
Quora
quora.com › How-do-I-compare-a-JSON-object-with-a-string-in-Java
How to compare a JSON object with a string in Java - Quora
Answer (1 of 3): Hopefully you are using a JSON library such as Jsonb or Gson. Your best option is to convert the String to JSON, then convert both JSON objects to class instances, then compare the instances with the class’s equals method. This would be something like the following in Jsonb: [c...
🌐
JSON Diff
jsondiff.com
JSON Diff - The semantic JSON compare tool
Validate, format, and compare two JSON documents. See the differences between the objects instead of just the new lines and mixed up properties.
🌐
Quora
quora.com › How-do-I-compare-two-JSON-which-has-different-structures-using-Java
How to compare two JSON which has different structures using Java - Quora
However, one approach could be to first convert the JSON strings to Java objects using a library such as Jackson, and then compare the resulting objects using the equals() method.
Top answer
1 of 16
204

Try Skyscreamer's JSONAssert.

Its non-strict mode has two major advantages that make it less brittle:

  • Object extensibility (e.g. With an expected value of {id:1}, this would still pass: {id:1,moredata:'x'}.)
  • Loose array ordering (e.g. ['dog','cat']==['cat','dog'])

In strict mode it behaves more like json-lib's test class.

A test looks something like this:

@Test
public void testGetFriends() {
    JSONObject data = getRESTData("/friends/367.json");
    String expected = "{friends:[{id:123,name:\"Corby Page\"}"
        + ",{id:456,name:\"Solomon Duskis\"}]}";
    JSONAssert.assertEquals(expected, data, false);
}

The parameters in the JSONAssert.assertEquals() call are expectedJSONString, actualDataString, and isStrict.

The result messages are pretty clear, which is important when comparing really big JSON objects.

2 of 16
107

As a general architectural point, I usually advise against letting dependencies on a particular serialization format bleed out beyond your storage/networking layer; thus, I'd first recommend that you consider testing equality between your own application objects rather than their JSON manifestations.

Having said that, I'm currently a big fan of Jackson which my quick read of their ObjectNode.equals() implementation suggests does the set membership comparison that you want:

public boolean equals(Object o)
{
    if (o == this) return true;
    if (o == null) return false;
    if (o.getClass() != getClass()) {
        return false;
    }
    ObjectNode other = (ObjectNode) o;
    if (other.size() != size()) {
        return false;
    }
    if (_children != null) {
        for (Map.Entry<String, JsonNode> en : _children.entrySet()) {
            String key = en.getKey();
            JsonNode value = en.getValue();

            JsonNode otherValue = other.get(key);

            if (otherValue == null || !otherValue.equals(value)) {
                return false;
            }
        }
    }
    return true;
}
🌐
Baeldung
baeldung.com › home › json › jackson › compare two json objects with jackson
Compare Two JSON Objects with Jackson | Baeldung
January 8, 2024 - JsonNode.equals works quite well in most cases. Jackson also provides JsonNode.equals(comparator, JsonNode) to configure a custom Java Comparator object. Let’s understand how to use a custom Comparator. Let’s look at how to use a custom Comparator to compare two JSON elements having numeric ...
🌐
GitHub
github.com › fslev › json-compare
GitHub - fslev/json-compare: A Java library for comparing JSONs · GitHub
String expectedString = "{\"a\":1, \"b\": [4, \"ipsum\", \"\\\\d+\"]}"; // actual represented as Map Map<String, Object> actualMap = new HashMap<>(); actualMap.put("a", 1); actualMap.put("b", Arrays.asList("ipsum", 4, 5)); actualMap.put("c", true); JSONCompare.assertMatches(expectedString, actualMap); // assertion passes · By default, JSONCompare rules out the Json sizes and also the order of elements from an array. This behaviour can be overridden by using the following compare modes: ... // Expected Json is included in actual Json String expected = "{\"b\": \"val1\"}"; String actual = "{\"a
Starred by 75 users
Forked by 14 users
Languages   Java
🌐
javaspring
javaspring.net › blog › ignore-specific-node-within-array-when-comparing-two-json-in-java
How to Compare Two JSON Strings in Java 8 and Ignore Specific Nodes Within Arrays Using JSONAssert — javaspring.net
Comparing JSON strings in Java 8 is streamlined with JSONAssert, but ignoring specific nodes within arrays requires custom logic. By creating a IgnoreArrayNodesComparator, you can dynamically ignore fields like id or timestamp in array elements ...
Find elsewhere
🌐
Medium
medium.com › threadsafe › how-to-compare-two-json-structures-in-java-when-the-order-of-fields-keeps-changing-f844df37e45a
How to compare two JSON objects in Java tests and when the order of values is not important | ThreadSafe
June 17, 2025 - When I am writing tests to confirm the JSON structure generated in the API with the expected structure, I almost always prefer to use the JSON path for this job, but In some scenarios, you can’t use the JSON path and write one assertion for each field in the expected JSON result, for example when your API produces a very large JSON response. In these cases, maybe it is a good idea to have the expected JSON output in a file and then compare the produced JSON result with that to confirm that the result is identical to the content of the expected JSON file.
🌐
javaspring
javaspring.net › blog › getting-a-diff-of-two-json-strings-using-java-code
How to Get a Diff of Two JSON Strings in Java: Top Libraries & Code Examples — javaspring.net
Overview: Javers is a popular library for diffing and auditing Java objects. While primarily designed for object diffing, it can also compare JSON strings by parsing them into maps or custom POJOs.
🌐
Baeldung
baeldung.com › home › json › compare two json objects with gson
Compare Two JSON Objects with Gson | Baeldung
January 8, 2024 - Each of those subclasses (JsonObject, JsonArray, etc.) overrides the Object.equals method, providing an effective deep JSON comparison. Suppose we have two strings, representing simple JSON objects, where the order of keys is different: ... ...
🌐
CodingTechRoom
codingtechroom.com › question › compare-json-strings-java
How to Compare Two JSON Strings in Java for Differences - CodingTechRoom
Use a JSON parsing library like `org.json` to create JSON objects from the strings. Iterate over the keys of the first JSON and compare them with the second.
🌐
Cassiomolin
cassiomolin.com › programming › comparing-json-documents-in-java
Comparing JSON documents in Java — Cássio Mazzochi Molin
July 23, 2018 - Once JSON documents are a set of key/value pairs, my first approach was to read the JSON documents as Map<K,V> instances and then compare them. Reading the JSON documents as Map<K,V> it’s pretty straightforward with both Jackson and Gson, the most popular JSON parsers for Java: ObjectMapper mapper = new ObjectMapper(); TypeReference<Map<String, Object>> type = new TypeReference<Map<String, Object>>() {}; Map<String, Object> leftMap = mapper.readValue(leftJson, type); Map<String, Object> rightMap = mapper.readValue(rightJson, type);
🌐
Stack Overflow
stackoverflow.com › questions › 46738702 › compare-two-json-strings-and-print-differences-between-them-using-java
Compare two json strings and print differences between them using Java - Stack Overflow
Rght now I am doing String compareTo but that doesn't tell what the differences are. ... You can instantiate those json objects as java POJOs and have a method or a static method in the class to compare and provide the results you need.
🌐
GitHub
gist.github.com › 95c58862f54cee57ae68e58bee2378f2
Compare two JSON Objects and get Difference. · GitHub
Compare two JSON Objects and get Difference. GitHub Gist: instantly share code, notes, and snippets.
🌐
Medium
medium.com › @mujtabauddinfurqan › what-i-learned-while-comparing-two-jsons-1150ae902b2c
What I learned while comparing two JSONs | by Mujtabauddin Furqan | Medium
February 23, 2019 - There are many ways to compare two JSONs, a lot of them involve converting them two Flat Maps or HashMaps The first and the most convenient one we tried was Guava’s Flat Map method · Guava is a common Utility library by Google made open source(Fucking awesome people) . If you deserialize the objects as a Map<String, Object>, you can compare two JSONs , you can use Maps.difference to compare the two resulting maps.
🌐
Makeseleniumeasy
makeseleniumeasy.com › 2021 › 02 › 19 › rest-assured-tutorial-68-compare-two-json-using-jackson-java-library
REST Assured Tutorial 68 – Compare Two JSON using Jackson – Java Library
February 19, 2021 - This means that it is possible to compare complete JSON trees for equality by comparing the equality of root nodes. equals() method is an abstract method and implemented by ObjectNode and ArrayNode classes. We need to convert the given JSON to JsonNode ( or ObjectNode or ArrayNode) first and ...