Rest Assured提取JSON中accountId返回null,如何正确取值存入字符串列表
问题根因
你原有代码的提取路径accountId直接从JSON根节点查找目标字段,但你需要的accountId实际嵌套路径为:根节点→identifiers对象→identifier数组→数组项的accountId字段,路径层级不匹配导致返回结果为null。
修正方案
将提取路径替换为identifiers.identifier.accountId即可,Rest Assured的path()方法会自动遍历identifier数组的所有元素,提取每个元素的accountId字段值,组装为字符串列表返回。
修正后的完整代码如下:
// https://svc-uat-cdw/cdw/counterparties.json?2021-05-25?limit=74000&count=false&sort=accountId public static List<String> JSONcounterparties(String date ) { baseURI = uri; List<String> accounts = given() .auth().basic(getJiraUser(), getJiraPass()) .param("date", date) .param("limit", "100") .param("count", "false") .param("sort", "accountId") .when() .get("/counterparties.json") .then() .extract().path("identifiers.identifier.accountId"); return accounts; }
补充说明
如果你的接口返回的是多个交易对手对象组成的数组结构,提取后可能得到嵌套的列表,可通过流式操作拍平:
List<List<String>> nestedAccounts = given()...extract().path("identifiers.identifier.accountId"); List<String> flatAccounts = nestedAccounts.stream() .flatMap(Collection::stream) .toList();
内容的提问来源于stack exchange,提问作者Bruno Lorena
相关产品推荐
相关产品推荐

