Rest Assured用JsonPath取system类型workflow id时JSON表达式报错
错误原因
你使用的JSONPath过滤语法[?(@.type =='system')]属于标准JSONPath规范,但RestAssured框架自带的jsonPath()方法默认使用基于Groovy的GPath表达式解析,不支持标准JSONPath的过滤语法,因此会抛出语法解析异常。你在在线工具测试通过是因为这类工具大多兼容标准JSONPath规范,和RestAssured内置的解析器实现不一致。
解决方案
方案1:使用RestAssured原生GPath语法(推荐,无需额外依赖)
直接用Groovy GPath的过滤写法替换原表达式即可,修改后的代码如下:
public static int getSystemWorkflowId(final Map<String, String> cookies) { return workflow.get(cookies).then().extract().jsonPath().getInt("workflows.find { it.type == 'system' }.id"); }
如果存在多个符合条件的工作流,需要取第一个的话可以用findAll搭配索引:
getInt("workflows.findAll { it.type == 'system' }[0].id")
方案2:切换为标准JSONPath解析器
如果你需要复用已有的标准JSONPath表达式,可以切换为支持标准JSONPath的解析器实现,步骤如下:
- 引入Jayway JsonPath依赖(以Maven为例):
<dependency> <groupId>com.jayway.jsonpath</groupId> <artifactId>json-path</artifactId> <version>2.8.0</version> <scope>test</scope> </dependency>
- 修改代码使用Jayway JsonPath解析响应:
public static int getSystemWorkflowId(final Map<String, String> cookies) { String responseBody = workflow.get(cookies).then().extract().asString(); return JsonPath.read(responseBody, "$..workflows[?(@.type =='system')].id"); }
内容的提问来源于stack exchange,提问作者Txili
相关产品推荐
相关产品推荐

