RestAssured如何构建路径获取JSON数组中指定位置的目标对象值
解决方法
RestAssured 内置的 JSONPath 规则里,数组索引从0开始计数,要提取数组内第二个对象,直接在对应数组字段后加[1]即可调整取值路径。
场景1:仅需获取第二个对象的id值
你可以直接修改取值路径,不需要再调用嵌套列表转普通列表的方法,调整后代码如下:
public static String JSON_UltimateParent(String parent) { baseURI = uri; return given() .auth().basic(getJiraUser(), getJiraPass()) .param("limit", "74000000") .param("count", "false") .param("sort", "accountId") .when() .get("/counterparties.json?"+ parent) .then() .extract().path("riskUltimateParent[1].identifier.id"); }
场景2:需要保留原方法返回List的结构,仅返回包含第二个id的列表
调整后代码如下:
public static List<String> JSON_UltimateParent(String parent) { baseURI = uri; String secondId = given() .auth().basic(getJiraUser(), getJiraPass()) .param("limit", "74000000") .param("count", "false") .param("sort", "accountId") .when() .get("/counterparties.json?"+ parent) .then() .extract().path("riskUltimateParent[1].identifier.id"); List<String> ultimates = new ArrayList<>(); ultimates.add(secondId); return ultimates; }
补充说明
- 如果
identifier字段本身也是数组,你需要取第二个identifier下的id,可以继续叠加索引,取值路径改为riskUltimateParent[1].identifier[1].id即可。 - 如果
identifier是数组类型,riskUltimateParent[1].identifier.id返回的是List<String>类型,你可以根据实际返回结构调整返回值类型,不需要再调用原有的嵌套列表转换方法。
内容的提问来源于stack exchange,提问作者Bruno Lorena
相关产品推荐
相关产品推荐

