[英]How to extract item from nested list - Rest Assured
I've got this json object 我有这个json对象
{
"type" : "employee",
"columns" :
[
{
"id" : 1,
"human" :
[
{
"name" : "ANA",
"age" : "23"
},
{
"name" : "IULIA",
"age" : "22"
}
]
},
{
"id" : 2,
"human" :
[
{
"name" : "ADI",
"age" : "21"
},
{
"name" : "GELU",
"age" : "18"
}
]
}
]
}
and I need to extract the first name from each human list. 我需要从每个人名单中提取名字。 I've tried
.body("columns.human.name[0]", everyItem(containsString("A")))
but it doesn't work. 我试过
.body("columns.human.name[0]", everyItem(containsString("A")))
但它不起作用。 Any ideas? 有任何想法吗?
Using JsonPath
you can get all columns and all humans. 使用
JsonPath
您可以获得所有列和所有人类。
Each of JSON Object
is represented as HashMap<>
. 每个
JSON Object
都表示为HashMap<>
。 If it contains only fields it's HashMap<String, String>
but if contains arrays or nested JSON Objects then it is HashMap<String, Object>
where Object
is either another JSON Object or array. 如果它只包含字段,那么它是
HashMap<String, String>
但是如果包含数组或嵌套的JSON对象,则它是HashMap<String, Object>
,其中Object
是另一个JSON对象或数组。
Given the above you can use following code to get all columns and name of first human in each column: 鉴于上述情况,您可以使用以下代码获取每列中第一个人的所有列和名称:
JsonPath path = response.jsonPath();
List<HashMap<String, Object>> columns = path.getList("columns");
for (HashMap<String, Object> singleColumn : columns) {
List<HashMap<String, Object>> humans = (List<HashMap<String, Object>>) singleColumn.get("human");
System.out.println(humans.get(0).get("name"));
}
The above code will print ANA
and ADI
in the console. 上面的代码将在控制台中打印
ANA
和ADI
。 You can store the results in List<String>
for further processing 您可以将结果存储在
List<String>
以进行进一步处理
you can get all "name" from humans with jsonPath : $.columns[*].human[*].name
it will give below result : 你可以通过jsonPath获取人类的所有“名字”:
$.columns[*].human[*].name
它将给出以下结果:
[
"ANA",
"IULIA",
"ADI",
"GELU"
]
And if you want only first "name" then you need to use josn : $.columns[*].human[0].name
this will give you below result: 如果你只想要第一个“名字”,那么你需要使用josn:
$.columns[*].human[0].name
这将给你以下结果:
[
"ANA",
"ADI"
]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.