如何使用 Rest Assured 基于条件获取 JSON 字段(节点)?
我们可以使用 Rest Assured 基于条件获取 JSON 字段(节点)。首先,我们将从请求中获取一个 JSON 格式的响应体。然后将其转换为字符串。
这是借助 JSONPath 类完成的。要解析 JSON 响应,我们必须首先将响应转换为字符串。
要获取响应,我们需要使用 Response.body 或 Response.getBody 方法。这两种方法都是 Response 接口的一部分。
获取响应后,将使用 asString 方法将其转换为字符串。此方法是 ResponseBody 接口的一部分。然后,我们将借助 jsonPath 方法从响应体中获取 JSON 表示形式。
我们将通过 Postman 向模拟 API URL 发送 GET 请求并观察其响应。

使用 Rest Assured,让我们获取 State 值为纽约的 zip 字段的值。
示例
代码实现
import static io.restassured.RestAssured.given;
import org.testng.annotations.Test;
import io.restassured.RestAssured;
import io.restassured.path.json.JsonPath;
import io.restassured.response.Response;
public class NewTest {
@Test
public void jsonValueCondition() {
//base URI with Rest Assured class
RestAssured.baseURI = "https://run.mocky.io/v3";
//obtain Response from GET request
Response res = given()
.when()
.get("/8ec8f4f7-8e68-4f4b-ad18-4f0940d40bb7");
//convert JSON to string
JsonPath j = new JsonPath(res.asString());
//get values of JSON array after getting array size
int s = j.getInt("Location.size()");
for(int i = 0; i < s; i++) {
String state = j.getString("Location["+i+"].State");
//check if condition meets
if(state.equalsIgnoreCase("New York")) {
String zip = j.getString("Location["+i+"].zip");
System.out.println(zip);
break;
}
}
}
}输出

广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP