如何使用 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