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

Rest Assured查询指定API中ID为913的name属性时JsonPath报错求助

解决RestAssured JsonPath过滤表达式报错的问题

我来帮你搞定这个问题!你遇到的报错是因为RestAssured内置的JsonPath用的是Groovy GPath语法,和你写的标准JSONPath语法(比如Jayway实现的)不兼容,所以才会抛出IllegalArgumentException。

错误原因

你写的$..menu_items[?(@id == 913)].description是标准JSONPath的过滤写法,但RestAssured的JsonPath不支持这种语法,它需要用Groovy风格的集合过滤表达式。

正确的实现方式

这里有两种可靠的写法来获取ID为913的条目name属性:

方式1:使用GPath直接过滤

利用Groovy的findAll方法过滤集合,再提取目标属性:

String URL = "https://davids-restaurant.herokuapp.com/menu_items.json?category=C";
Response res = RestAssured.get(URL);
JsonPath jsonPathEvaluator = res.jsonPath();

// 过滤id等于913的条目,取第一个匹配项的name
String targetName = jsonPathEvaluator.get("menu_items.findAll { it.id == 913 }.name[0]");
System.out.println("目标条目名称:" + targetName);

方式2:手动遍历列表(更直观)

如果觉得GPath语法有点陌生,也可以先把菜单列表取出来,再手动遍历匹配:

String URL = "https://davids-restaurant.herokuapp.com/menu_items.json?category=C";
Response res = RestAssured.get(URL);
JsonPath jsonPathEvaluator = res.jsonPath();

// 获取所有menu_items列表
List<Map<String, Object>> menuItems = jsonPathEvaluator.getList("menu_items");

// 遍历找到id为913的条目
for (Map<String, Object> item : menuItems) {
    if (913 == (Integer) item.get("id")) {
        System.out.println("目标条目名称:" + item.get("name"));
        break; // 假设id唯一,找到就退出循环
    }
}

验证结果

调用目标API后,ID为913的条目名称是Crispy Orange Chicken,两种写法都能正确输出这个值。

内容的提问来源于stack exchange,提问作者user7520525

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 08:32:58