【发布时间】:2019-12-07 21:26:45
【问题描述】:
我希望从数组和对象的 JSON 路径中提取某些值,并将这些值用于进一步处理,并且正在努力访问这些元素。这是 JSON 响应:
[
{
"od_pair":"7015400:8727100",
"buckets":[
{
"bucket":"C00",
"original":2,
"available":2
},
{
"bucket":"A01",
"original":76,
"available":0
},
{
"bucket":"B01",
"original":672,
"available":480
}
]
},
{
"od_pair":"7015400:8814001",
"buckets":[
{
"bucket":"C00",
"original":2,
"available":2
},
{
"bucket":"A01",
"original":40,
"available":40
},
{
"bucket":"B01",
"original":672,
"available":672
},
{
"bucket":"B03",
"original":632,
"available":632
},
{
"bucket":"B05",
"original":558,
"available":558
}
]
}
]
我尝试使用 $ 访问根元素,但无法进一步使用它。
这是我写的测试方法。我想提取 od_pair 的值,并且在每个 od_pair 中,我需要能够检索存储桶代码及其可用编号。
public static void updateBuckets(String ServiceName, String DateOfJourney) throws Exception {
File jsonExample = new File(System.getProperty("user.dir"), "\\LogAvResponse\\LogAvResponse.json");
JsonPath jsonPath = new JsonPath(jsonExample);
List<Object> LegList = jsonPath.getList("$");
// List<HashMap<String, String>> jsonObjectsInArray = jsonPath.getList("$");
int NoofLegs = LegList.size();
System.out.println("No of legs :" + NoofLegs);
for (int j = 0; j <= NoofLegs; j++)
// for (HashMap<String, String> jsonObject : jsonObjectsInArray) {
{
String OD_Pair = jsonPath.param("j", j).getString("[j].od_pair");
// String OD_Pair = jsonObject.get("od_pair");
System.out.println("OD Pair: " + OD_Pair);
List<Object> BucketsList = jsonPath.param("j", j).getList("[j].buckets");
int NoOfBuckets = BucketsList.size();
// System.out.println("OD Pair: " + OD_Pair);
System.out.println("no of Buckets: " + NoOfBuckets);
for (int i = 0; i < NoOfBuckets; i++) {
String BucketCode = jsonPath.param("j", j).param("i", i).getString("[j].buckets[i].bucket");
String Available = jsonPath.param("j", j).param("i", i).getString("[j].buckets[i].available");
int BucketCodeColumn = XLUtils.getBucketCodeColumn(BucketCode);
int ServiceRow = XLUtils.getServiceRow(ServiceName, DateOfJourney, OD_Pair);
System.out.println("Row of " + ServiceName + ":" + DateOfJourney + "is:" + ServiceRow);
System.out.println("Bucket Code column of " + BucketCode + " is: " + BucketCodeColumn);
XLUtils.updateAvailability(ServiceRow, BucketCodeColumn, Available);
}
}
}
}
这是我看到的错误:
Caused by:
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup
failed:
Script1.groovy: 1: unexpected token: [ @ line 1, column 27.
restAssuredJsonRootObject.[j].od_pair
有人可以帮帮我吗?
【问题讨论】:
-
I need to be able to retrieve the bucket codes and their available numbers.基于od_pair,对吧? -
我希望不仅能够访问 od_pair 还能够访问其中的存储桶对象。所以每个 od_pair 都有很多桶作为对象。使用您的 Hashmap 解决方案,我不确定如何访问每个 od_pairs 中的各种存储桶
-
是的,这是正确的@Fenio
-
好的,知道了。有一些解决方案,但我会向您展示扩展的和最好的(在我看来)一个。我需要几分钟
-
@Fenio:所以基本上我正在尝试运行嵌套的 for 循环,一个用于获取 od_pair 并在其中一个用于存储桶的 for 循环以获取每个存储桶代码和可用编号。抱歉,因为我是新手,因此我的一些问题在这里可能听起来很幼稚。
标签: rest-assured rest-assured-jsonpath