Find JSON object in JSON array

Dexter Denmark :

I have a goal to verify that certain JSON that I've got from RabbitMQ corresponds to one of expected JSONs in an array in a single file.

In other words, I need to verify that this JSON:

{
  "networkCode":"network",
  "programId":"92000"
}

is present in this JSON array:

[
{
   "networkCode":"network",
   "programId":"92000"
},
{
   "networkCode":"network",
   "programId":"92666"
}
]

Thank you very much for help!

Some part of my code

//GET DESIRABLE JSON
String message = new String(delivery.getBody(), StandardCharsets.UTF_8);
            JSONObject myJSON= new JSONObject(message);

//GET THE JSON ARRAYS FROM FILE
            JSONParser parser = new JSONParser();
            Object expectedJSONs= parser.parse(new FileReader("C:\\amqpclient\\src\\test\\java\\tradeDoubler\\ExpectedDTO.json"));
            JSONArray expectedArray = (JSONArray) expectedJSONs;

            JSONAssert.assertEquals(
                    myJSON, expectedArray , JSONCompareMode.LENIENT);

Compilation says that cannot resolve this

Exception in thread "main" java.lang.AssertionError: Expecting a JSON array, but passing in a JSON object

BCh :

Org.json library is quite easy to use.

Example code below:

import org.json.*;

JSONObject obj = new JSONObject(" yourJSONObjectHere ");

JSONArray arr = obj.getJSONArray("networkArray");
for (int i = 0; i < arr.length(); i++)
{
    String networkCode = arr.getJSONObject(i).getString("networkCode");
    ......
}

By iterating on your JSONArray, you can check if each object is equal to your search.

You may find more examples from: Parse JSON in Java

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=135273&siteId=1