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

RestAssured中JsonPath表达式无效异常问题求助

解决RestAssured JsonPath表达式无效的问题

问题原因

RestAssured自带的io.restassured.path.json.JsonPath基于Groovy的GPath语法实现,和你在在线工具中使用的标准JsonPath(如Jayway实现)语法不兼容,直接套用标准表达式会触发无效表达式异常。

解决方案

方案1:适配RestAssured的GPath语法

针对你的需求(从数组元素的tags数组中筛选id=0的元素),使用GPath语法改写表达式:

JsonPath jsonPathEvaluator = response.jsonPath();
// 先展开所有tags数组,再筛选id为0的元素
ArrayList result = jsonPathEvaluator.get("tags.flatten().findAll { it.id == 0 }");

如果原响应是顶级数组(而非对象内的数组),调整为:

ArrayList result = jsonPathEvaluator.get("*.tags.flatten().findAll { it.id == 0 }");

方案2:切换为标准JsonPath(Jayway)实现

若想继续使用原有表达式,可引入Jayway的JsonPath依赖,用标准语法解析:

  1. 添加Maven依赖(版本可按需调整):
<dependency>
    <groupId>com.jayway.jsonpath</groupId>
    <artifactId>json-path</artifactId>
    <version>2.8.0</version>
</dependency>
  1. 代码中使用Jayway的API解析响应:
import com.jayway.jsonpath.JsonPath;

// 将响应转为字符串
String responseBody = response.getBody().asString();
// 使用原表达式查询
ArrayList result = JsonPath.read(responseBody, "$[*]['tags'][?(@.id==0)]");

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 06:46:02