如何在巢狀的 JSON 中使用 Rest Assured 獲取 JSON 陣列欄位?


我們可以使用 Rest Assured 在巢狀的 JSON 中獲取 JSON 陣列欄位。首先,我們要從請求中獲取一個 JSON 格式的響應內容。然後將其轉換為字串。

最後,要獲取特定的陣列值,我們要使用陣列索引後跟欄位名。我們將在模擬 API 上透過 Postman 傳送 GET 請求,並觀察響應。

使用 Rest Assured,讓我們獲取值 49086 的第二個 zip 欄位。它是 Location 陣列中第二個 JSON 的一部分。我們將透過遍歷路徑 Location[1].zip 來獲取第二個 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 jsonAryValue() {

      //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());

      //Zip for 2nd Location array
      String zip = j.getString("Location[1].zip");
      System.out.println("Zip for 2nd Location array: " + zip);
   }
}

輸出

更新於:2021 年 11 月 17 日

5,000+ 閱讀

開啟你的 職業生涯

完成課程,獲得認證

開始吧
廣告