0

I'm attempting to access an object in an Json response, but not sure how. How can I access ID 11 using rest-assured, where ObjID1 and ObjID2 are unique UUID's?

       "ObjID1": [
            {
                "ID": "11",
                "NAME": "XYZ",
                "GENDER": "M"
            }
        ]

        "ObjID2": [
            {
                "ID": "12",
                "NAME": "Z",
                "GENDER": "F"
            }
        ]


1 Answer 1

1

To assert element's value you can use

then().body("ObjID1.ID[0]", equalTo("11"))

Indexing ID field with [0] allows you to get the ID of first JSON Object in the Array.

If you want to get this value for further processing then you can extract it like this:

JsonPath path = JsonPath.from("json file or json String");
List<HashMap<String, Object>> listOfJsonObjects = path.get("ObjID1");

We parsed the JSON and by using the path.get method we save Array of JSON Objects inside List of HashMaps. Each element in the list is the JSON Object.

In order to access first JSON Object you can use

HashMap<String, Object> jsonObject = listOfJsonObjects.get(0);

and then, using classic HashMap methods you can get specific element in the JSON Object like this:

jsonObject.get("ID");

The above will return "11" Note that you will have to make a cast to String to get the value. Values in the HashMap are objects because JSON Objects in the array may contain nested Arrays or Objects.

String firstId = (String) jsonObject.get("ID");
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.