Search code examples
javajsonjsonassert

Using JSONAssert to check if an item exists in a JSON array


I have a JSONObject that is similar to something like this:

{
 "category":"abc"
 "staus":""open"
 "external":[
       {"name":"123", "type":"OTHER"},
       {"name":"678", "type":"ALPHA"},
       {"name":"890", "type":"DELTA"}
 ]
}

If I want to use JSONAssert to check if the item {"name":"678"} exists and I don't know the item's order and the number of items in the "external" array, how should I do in Java?

It seems the ArrayValueMatcher should be the way to go but I just cannot get it works.

Please help


Solution

  • You could use JsonPath for this usecase :

    JSONArray array = JsonPath.read(json, "$.external[?(@.name == '678')]");
    Assertions.assertThat(array).hasSize(1);