Alex
Alex

Reputation: 33

Comparing two JsonArray nodes in Java

I have a method that gets two Json nodes that should be Json array nodes of different sizes. I need to check if ArrayA contains all the elements of ArrayB. How do I do that?

private boolean isContains (JsonNode ArrayA, JsonNode ArrayB) {

    if (ArrayA.isArray() && ArrayB.isArray()) {
        // Here goes the missing code.
    }
}

Upvotes: 0

Views: 5484

Answers (4)

Timur Kondratyev
Timur Kondratyev

Reputation: 1

For those who faced the same problem but prefer more flat code. You can use the Apache Commons's IterableUtils.toList() to convert the ArrayNode#elements() to List and then perform List#containsAll() operation to check whether they contain the same elements. It will look like this:

sourceArray.size() == targetArray.size() && IteratorUtils.toList(sourceArray.elements()).containsAll(IteratorUtils.toList(targetArray.elements()))

Upvotes: 0

Gopi Vishwakarma
Gopi Vishwakarma

Reputation: 149

You can use zjsonpatch library, which presents the diff information in accordance with RFC 6902 (JSON Patch). Its very easy to use. Please visit its description page for its usage. This library is better than fge-json-patch (which was mentioned in above answer) because it can detect correctly items being inserted/removed from arrays.

Upvotes: 0

ced-b
ced-b

Reputation: 4065

There seems to be no inbuilt method I can see, but JsonNode implements Iteratable so you can loop through both and do a compare. Something along the lines of:

boolean matches = true;

for (JsonNode nodeB : arrayB)
{
   boolean matchesInternal = false;

   for (JsonNode nodeA : arrayA)
   {
      if (nodeA.equals(nodeB))
      {
          matchesInternal = true;
          break;
      }
   }

   if (!matchesInternal) {
      matches = false;
      break;
   }
}

return matches;

Upvotes: 0

Gábor Bakos
Gábor Bakos

Reputation: 9100

The JSON Patch reverse part might do what you are looking for.

See: https://github.com/fge/json-patch#json-diff-factorization

Edit: It is as easy as:

JsonNode diff = JsonDiff.asJson(first, second);

And than you can check whether diff contains removes or adds or both.

Upvotes: 2

Related Questions