1

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

Wonderjimmy
  • 499
  • 1
  • 6
  • 15

2 Answers2

0

You could use JsonPath for this usecase :

JSONArray array = JsonPath.read(json, "$.external[?(@.name == '678')]");
Assertions.assertThat(array).hasSize(1);
Camille Vienot
  • 727
  • 8
  • 6
0

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")));
    }
Tim Malich
  • 1,301
  • 14
  • 22