如何使用 Rest Assured 在巢狀 JSON 中獲取 JSON 欄位?
我們可以使用 Rest Assured 從一個複雜的巢狀 JSON 中獲取 JSON 欄位。首先,我們將從一個請求中獲取一個 JSON 格式的響應主體。然後將其轉換為字串。
我們將透過 Postman 在一個模擬 API URL 上傳送一個 GET 請求並觀察它的響應。
使用 Rest Assured,讓我們獲取 Price 欄位的值,其值為 $150。它是 Items 的一部分。我們將透過遍歷 Items.Price 路徑獲取 Item Count 欄位的值。
示例
程式碼實現
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 jsonValue() { //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 a field value from nested JSON String p = j.getString("Items.Price"); System.out.println("Price is: " + p); } }
輸出
廣告