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

2.4k Views Asked by At

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

2

There are 2 best solutions below

1
On BEST ANSWER

You could use JsonPath for this usecase :

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

Here is a complete example using JsonAssert:

 @Test
 public void foo() throws Exception {
     String jsonString = "{\n" +
             " \"category\":\"abc\",\n" +
             " \"staus\":\"open\",\n" +
             " \"external\":[\n" +
             "       {\"name\":\"123\", \"type\":\"OTHER\"},\n" +
             "       {\"name\":\"678\", \"type\":\"ALPHA\"},\n" +
             "       {\"name\":\"890\", \"type\":\"DELTA\"}\n" +
             " ]\n" +
             "}";
        
    JsonAssert.with(jsonString).assertThat("$.external[*].name", hasItem(equalTo("678")));
    }