You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 07:54:03