从 JSON 对象数组中提取元素

huangapple go评论64阅读模式
英文:

Extract element from json object array

问题

我有以下的 JSON 响应。在 layer2 对象数组下方,可以有 x 个项目。

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

我的要求是,如果我知道一个元素的值(例如 item1 的值为 result4),我如何获取对应的 item1 的项目值,即 result3

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

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

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

{&quot;data&quot;: {
        &quot;layer1&quot;: {
            &quot;layer2&quot;: [
                {
                    &quot;item1&quot;: &quot;result1&quot;,
                    &quot;item2&quot;: &quot;result2&quot;
				},
				{
                    &quot;item1&quot;: &quot;result3&quot;,
                    &quot;item2&quot;: &quot;result4&quot;
				}
				]
			}
		}
}

My requirement is if I know value of one element (e.g. 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&lt;Object&gt; actual = response.jsonPath().getList(&quot;data.layer1.layer2&quot;);

答案1

得分: 1

我认为你的意思是,如果item2是result4,则找到item1。根据你编写的代码,你可以遍历列表,将对象强制转换为映射,然后检查item2是否存在且其值为result4,然后获取item1。

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

附注:我尚未测试过这段代码,但从逻辑上讲应该可以工作。

英文:

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(&quot;item2&quot;).equals(&quot;result4&quot;)){
        return ((Map)item).get(&quot;item1&quot;);
     } 
}

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

huangapple
  • 本文由 发表于 2020年5月5日 15:38:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/61608054.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定