When both the objects are JSON Arrays, you are just comparing according to position of JSON objects, please find below code for correct at code,

else if (jsonElement1.isJsonArray() && jsonElement2.isJsonArray()) {
    JsonArray jarr1 = jsonElement1.getAsJsonArray();
    JsonArray jarr2 = jsonElement2.getAsJsonArray();
    if (jarr1.size() != jarr2.size()) {
      return false;
    } else {
      // Iterate JSON Array to JSON Elements
      for (JsonElement je1 : jarr1) {
        boolean flag = false;
        for(JsonElement je2 : jarr2){
         flag = compareJson(je1, je2);
         if(flag){
          jarr2.remove(je2);
          break; 
         }
        }
        isEqual = isEqual && flag;
      }
    }
  }
Answer from Rajani B on Stack Overflow
🌐
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.
🌐
Baeldung
baeldung.com › home › json › compare two json objects with gson
Compare Two JSON Objects with Gson | Baeldung
January 8, 2024 - Before we dive into comparing objects, let’s have a look at how Gson represents JSON data in Java. When working with JSON in Java, we first need to convert the JSON String into a Java object. Gson provides JsonParser which parses source JSON into a JsonElement tree: String objectString = "{\"customer\": {\"fullName\": \"Emily Jenkins\", \"age\": 27 }}"; String arrayString = "[10, 20, 30]"; JsonElement json1 = JsonParser.parseString(objectString); JsonElement json2 = JsonParser.parseString(arrayString);
🌐
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 ...
🌐
Netflix Open Source
netflix.github.io › msl › javadoc › com › netflix › msl › util › JsonUtils.html
JsonUtils (Message Security Layer Public API)
Performs a deep comparison of two JSON arrays for equality. Two JSON arrays are considered equal if both arrays contain the same number of elements, and all corresponding pairs of elements in the two arrays are equal. In other words, two JSON arrays are equal if they contain the same elements ...
🌐
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
Nested arrays (e.g., a[*].b[*].c). 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 using wildcard patterns (e.g., users[*].id).
🌐
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.
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;
}
Find elsewhere
🌐
Google Groups
groups.google.com › g › google-gson › c › qbgd8_Vb9w4
Is there a quick way to compare two json arrays?
July 31, 2012 - CompareArrays.java ==================== import java.util.*; import com.google.gson.*; public class CompareArray { static Set<JsonElement> setOfElements(JsonArray arr) { Set<JsonElement> set = new HashSet<JsonElement>(); for (JsonElement j: arr) { set.add(j); } return set; } public static void main(String[] args) { JsonParser parser = new JsonParser(); Set<JsonElement> arr1elems = setOfElements(parser.parse(args[0]).getAsJsonArray()); Set<JsonElement> arr2elems = setOfElements(parser.parse(args[1]).getAsJsonArray()); System.out.println("Arrays match? " + arr1elems.equals(arr2elems)); } } ==================== $ java -cp .:gson-2.2.2.jar CompareArray '[{"key1":"value1"}, {"key2":"value2"}, {"key3":"value3"}]' '[{"key3":"value3"}, {"key1":"value1"}, {"key2":"value2"}]' Arrays match?
🌐
Stack Overflow
stackoverflow.com › questions › 57069595 › how-do-i-compare-two-jsonarray-in-java
json - How do i compare two JSONArray in java? - Stack Overflow
July 17, 2019 - Maybe, achieve this by using JAVA Stream API. Please comment if you need any additional information. Thanks!! ... @Michal This is my requirement ..If any value matches from both the array the function must return a true value... or else it must return a false. ... You need intersection of two collections. Do you have possibility to get these JSONArrays into Collection, array or stream?
🌐
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 5
6

I have change a bit in your solution to get the wanted result.

I would do my difference check in List, therefore I will create method to change JSON to list of strings based on your code:

private static List<String> jsonToList(String json){
    List<String> list = new ArrayList<>();
    Gson gson = new Gson();
    Type type = new TypeToken<Map<String, Object>>(){}.getType();
    Map<String, Object> jsonMap = gson.fromJson(json, type);
    Map<String, Object> flatten = FlatMapUtil.flatten(jsonMap);
    flatten.forEach((k, v) -> list.add(v.toString()));
    return list;
}

Update
When I answered the question I did things a bit fast, the jsonToList was based on your code. As it is right now it is over complicated to what you are asking for. I have therefore made much lighter version using the following method in stead:

private static List<String> jsonToList(String json) {
    JSONObject response = new JSONObject(json);
    List<String> list = new ArrayList<>();
    JSONArray jsonArray = response.getJSONArray("categories");
    if (jsonArray != null) {
        for (int i = 0; i < jsonArray.length(); i++) {
            list.add(jsonArray.get(i).toString());
        }
    }
    return list;
}

That said, now you have two choices and it is up to you to find out which one fits best to your needs and take it from here.

End of Update


for this example I have made 3 test examples

String main = "{\"categories\":[\"May\",\"Apr\",\"Mar\"]}";
String json1 = "{\"categories\":[\"May\",\"May\",\"Apr\",\"Apr\",\"Mar\",\"Mar\"]}";
String json2 = "{\"categories\":[\"May\",\"Apr\",\"Apr\",\"Mar\",\"Mar\",\"Mar\"]}";
String json3 = "{\"categories\":[\"May\",\"Apr\",\"Mar\",\"Mar\"]}";

in my second step I will create a

List<String> mainList = jsonToList(main);
List<String> list1 = jsonToList(json1);

so far so good. Now I make a method to take the extra difference of the 2 list, that mean as you requested in your comments, we take only all values that are duplicated more than once and return them in list. In this method I used hashmap only count duplicates and than take the all that is repeated more than 1 time:

private static List<String> diffList(List<String> mainList, List<String> secondList){
    List<String> list = new ArrayList<String>();
    Map<String, Integer> wordCount = new HashMap<>();
    for(String word: secondList) {
        if(mainList.contains(word)) {
            Integer count = wordCount.get(word);
            wordCount.put(word, (count == null) ? 1 : count + 1);
            if(wordCount.get(word) > 1){
                list.add(word);
            }
        }
    }
    return list;
}

Finally I would test all cases, for instance for list1:

List<String> diff1 = diffList(mainList, list1);
for (String s : diff1) {
    System.out.println(s);
}

The output will be

May
Apr
Mar

for list2

Apr
Mar
Mar

And for list3

Mar

Now I will separate view method from the your method and create some thing like, just to make my code more clear and easy to work with:

private static String viewResult(List<String> list1, List<String> list2, List<String> duplicate){
    String result;
    StringBuilder SB = new StringBuilder("</br>");
    SB.append("Entries only on LEFT: </br>");
    list1.forEach(e -> SB.append(e + "</br>"));
    SB.append("Entries only on RIGHT: </br>");
    list2.forEach(e -> SB.append(e + "</br>"));
    SB.append("Entries full difference : </br>");
    duplicate.forEach(e -> SB.append(e + "</br>"));
    result = SB.toString();
    return result;
}

So if we put all this code together I will be some thing like this, and the following code is to demonstrate how things works, but from here you can take it to the next level in your code:

public static void main(String[] args) {
    String main = "{\"categories\":[\"May\",\"Apr\",\"Mar\"]}";
    String json1 = "{\"categories\":[\"May\",\"May\",\"Apr\",\"Apr\",\"Mar\",\"Mar\"]}";
    String json2 = "{\"categories\":[\"May\",\"Apr\",\"Apr\",\"Mar\",\"Mar\",\"Mar\"]}";
    String json3 = "{\"categories\":[\"May\",\"Apr\",\"Mar\",\"Mar\"]}";

    List<String> mainList = jsonToList(main);

    List<String> list1 = jsonToList(json1);
    List<String> diff1 = diffList(mainList, list1);
    for (String s : diff1) {
        System.out.println(s);
    }

    String view = viewResult(mainList, list1, diff1);
}

private static List<String> jsonToList(String json){
    List<String> list = new ArrayList<String>();
    Gson gson = new Gson();
    Type type = new TypeToken<Map<String, Object>>(){}.getType();
    Map<String, Object> jsonMap = gson.fromJson(json, type);
    Map<String, Object> flatten = FlatMapUtil.flatten(jsonMap);
    flatten.forEach((k, v) -> list.add(v.toString()));
    return list;
}

private static List<String> diffList(List<String> mainList, List<String> secondList){
    List<String> list = new ArrayList<String>();
    Map<String, Integer> wordCount = new HashMap<>();
    for(String word: secondList) {
        if(mainList.contains(word)) {
            Integer count = wordCount.get(word);
            wordCount.put(word, (count == null) ? 1 : count + 1);
            if(wordCount.get(word) > 1){
                list.add(word);
            }
        }
    }
    return list;
}

private static String viewResult(List<String> list1, List<String> list2, List<String> duplicate){
    String result;
    StringBuilder SB = new StringBuilder("</br>");
    SB.append("Entries only on LEFT: </br>");
    list1.forEach(e -> SB.append(e + "</br>"));
    SB.append("Entries only on RIGHT: </br>");
    list2.forEach(e -> SB.append(e + "</br>"));
    SB.append("Entries full difference : </br>");
    duplicate.forEach(e -> SB.append(e + "</br>"));
    result = SB.toString();
    return result;
}
2 of 5
2

If you want something more generic with a good diff you could utilize AssertJ here. Its usually used for Testing, but the diff looks really good and you can also use it in normal code.

Example:

Expecting:
  <["Mai", "Apr", "Mar"]>
to contain exactly in any order:
  <["May", "Apr", "Mar", "Mar"]>
elements not found:
  <["May", "Mar"]>
and elements not expected:
  <["Mai"]>

Can be created by:

[...]
import org.assertj.core.api.Assertions;

public class JsonTest {
    final static String arr = " [\n"+
            "            \"Mai\",\n"+
            "            \"Apr\",\n"+
            "            \"Mar\"\n"+
            "          ]";
    final static String arr2 = " [\n"+
            "            \"May\",\n"+
            "            \"Apr\",\n"+
            "            \"Mar\",\n"+
            "            \"Mar\"\n"+
            "          ]";

    public static void main(String[] args){
        System.out.println(smartJSONsCompare(arr,arr2));
    }

    private static String smartJSONsCompare(String leftJson, String rightJson) {
        Gson gson = new Gson();
        Type type = new TypeToken<List<String>>(){}.getType();
        List<String> left = gson.fromJson(leftJson, type);
        List<String> right = gson.fromJson(rightJson, type);
        try{
            Assertions.assertThat(left).containsExactlyInAnyOrderElementsOf(right);
        }catch(AssertionError  ae){
            return ae.getMessage();
        }
        return "Matched";
    }
  }

I added the dependencies in gradle with:

dependencies {
    compile("org.assertj:assertj-core:3.11.1")
}
🌐
Makeseleniumeasy
makeseleniumeasy.com › 2021 › 05 › 14 › rest-assured-tutorial-72-how-to-compare-part-of-json-objects-and-arrays-using-jsonassert-library
REST Assured Tutorial 72 – How To Compare Part of JSON Objects and Arrays using JSONassert library
May 14, 2021 - We need to compare that the ... in the second JSON Object. In this case, we just need to use the overloaded assertEquals() method with some methods with JsonPath to fetch the desired portion of JSON objects....
🌐
GitHub
github.com › fslev › json-compare
GitHub - fslev/json-compare: A Java library for comparing JSONs · GitHub
A Java library for matching JSONs, with some tweaks ! Compare any JSON convertible Java objects and check the differences between them when matching fails.
Starred by 75 users
Forked by 14 users
Languages   Java
🌐
Stack Overflow
stackoverflow.com › questions › 41330715 › deep-comparing-of-two-json-and-displaying-the-differences
java - Deep Comparing of two json and displaying the differences - Stack Overflow
May 24, 2017 - I am trying to compare two dynamic json data and if they are not equal then i am printing the differences. For this i am using · Type mapType = new TypeToken<Map<String, Object>>(){}.getType(); Map<String,Object> firstMap = g.fromJson(jsonElement1, mapType); Map<String, Object> secondMap = g.fromJson(jsonElement2, mapType); System.out.println(Maps.difference(firstMap, secondMap)); I need to display the difference in the console. This is the java code in which i am trying to display the differences of the json
🌐
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 - JSON is a set of key-value pairs wherein the order of the keys is never guaranteed But the order of any array in a JSON is guaranteed · 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
🌐
Medium
zarinfam.medium.com › 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.
🌐
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 - Equality for node objects is defined as a full (deep) value equality. 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.