简体   繁体   中英

Extract element from json object array

I have below json response. Below response for layer2 object array there can be x number of items

{"data": {
        "layer1": {
            "layer2": [
                {
                    "item1": "result1",
                    "item2": "result2"
                },
                {
                    "item1": "result3",
                    "item2": "result4"
                }
                ]
            }
        }
}

My requirement is if I know value of one element (eg item1 value result4 ), How do I get the correspondence item value of item1 which is result3 .

I have the below code where I can retrieve the object array. Is that possible to retrieve above with below output.

List<Object> actual = response.jsonPath().getList("data.layer1.layer2");

I think you meant if item2 is result4 then find item1. With the code you have written you can iterate the list and typecast the object to map and check if item2 exists with value result4 then get item1.

for(Object item: actual)
{
     if(((Map)item).get("item2").equals("result4")){
        return ((Map)item).get("item1");
     } 
}

PS: I haven't tested this code but logically it should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM