Rest-Assured兼容Jayway JsonPath表达式问题及GPath改写咨询
解决Rest-Assured中Jayway JsonPath表达式报错的问题
你遇到的问题根源很明确:Rest-Assured默认使用的是Groovy的GPath语法,而非Jayway风格的JsonPath,所以直接传入Jayway的表达式会触发语法解析错误。下面给你两种可行的解决方案:
方案一:改写为GPath表达式
GPath的过滤逻辑和Jayway略有不同,你原表达式对应的GPath写法如下:
public String readInbox(String emailAddress) { Response response = given().log().all().when().get(MESSAGES_ENDPOINT); JsonPath jsonPath = new JsonPath(response.asString()); // GPath写法:过滤出To[0].Mailbox等于'foobar'的items,再提取所有Body字段 String bodyContent = jsonPath.getString("items.findAll { it.To[0].Mailbox == 'foobar' }*.Body"); System.out.println(bodyContent); return bodyContent; }
findAll { ... }用于过滤符合条件的items元素*.Body是Groovy的spread operator,用来提取所有过滤后元素的Body属性值
方案二:让Rest-Assured直接使用Jayway JsonPath
如果你不想改写表达式,也可以配置Rest-Assured使用Jayway的JsonPath实现,步骤如下:
- 确保项目中已引入Jayway JsonPath的依赖(如果用Maven):
<dependency> <groupId>com.jayway.jsonpath</groupId> <artifactId>json-path</artifactId> <version>2.8.0</version> <!-- 使用最新稳定版即可 --> </dependency>
- 代码中配置Rest-Assured默认使用Jayway,或者直接使用Jayway的JsonPath类解析:
方式A:全局配置Rest-Assured使用Jayway
import io.restassured.RestAssured; import io.restassured.config.JsonConfig; import io.restassured.path.json.config.JsonPathConfig; import io.restassured.path.json.config.JsonPathImplementation; // 在测试初始化时配置 RestAssured.config = RestAssured.config() .jsonConfig(JsonConfig.jsonConfig() .jsonPathConfig(JsonPathConfig.jsonPathConfig() .defaultJsonPathImplementation(JsonPathImplementation.JAYWAY))); // 之后你的原有代码就可以正常运行了 public String readInbox(String emailAddress) { Response response = given().log().all().when().get(MESSAGES_ENDPOINT); JsonPath jsonPath = new JsonPath(response.asString()); String bodyContent = jsonPath.getString("$.items[?(@.To[0].Mailbox == 'foobar')]..Body"); System.out.println(bodyContent); return bodyContent; }
方式B:直接使用Jayway的JsonPath类解析
这种方式不需要修改全局配置,直接调用Jayway的API:
import com.jayway.jsonpath.JsonPath; public String readInbox(String emailAddress) { Response response = given().log().all().when().get(MESSAGES_ENDPOINT); // 直接用Jayway的JsonPath读取 String bodyContent = JsonPath.read(response.asString(), "$.items[?(@.To[0].Mailbox == 'foobar')]..Body"); System.out.println(bodyContent); return bodyContent; }
内容的提问来源于stack exchange,提问作者symon
相关产品推荐
相关产品推荐

