Java 从json对象数组中提取元素

Java 从json对象数组中提取元素,java,jsonpath,rest-assured-jsonpath,Java,Jsonpath,Rest Assured Jsonpath,下面是我的回复。在layer2对象数组的响应下面,可以有x个项目 {"data": { "layer1": { "layer2": [ { "item1": "result1", "item2": "result2" }, { "item1":

下面是我的回复。在layer2对象数组的响应下面,可以有x个项目

{"data": {
        "layer1": {
            "layer2": [
                {
                    "item1": "result1",
                    "item2": "result2"
                },
                {
                    "item1": "result3",
                    "item2": "result4"
                }
                ]
            }
        }
}
我的要求是,如果我知道一个元素的值(例如
item1
valueresult4),我如何获得
item1
的对应项值,即result3

我有下面的代码,可以在其中检索对象数组。是否可以用下面的输出检索上面的内容

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

我想你的意思是,如果item2是result4,那么找到item1。使用您编写的代码,您可以迭代列表并键入要映射的对象,检查是否存在值为result4的item2,然后获取item1

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

PS:我还没有测试过这段代码,但逻辑上它应该可以工作。

你能迭代
actual
并过滤你需要的对象吗?当你的JSON中只有
layer1
对象时,你为什么要使用
gridlayer1
?打字错误?@Fenio很抱歉这是个打字错误。纠正