如何在 Rest Assured 中獲取巢狀 JSON 中陣列的大小?


我們可以獲取 Rest Assured 中巢狀 JSON 中陣列的大小。最初,我們將獲取來自請求的 JSON 格式的 Response body。然後將其轉換成字串。

最後,要獲取 JSON 陣列大小,我們必須使用 size 方法。我們將在模擬 API 上透過 Postman 傳送 GET 請求,並檢視 Response。

利用 Rest Assured,我們可以獲取巢狀 JSON 響應中 Location 陣列的大小。大小應為 3,因為它包含三個位置的資訊 - 密歇根州、印第安納州和紐約州。

示例

程式碼實現

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 jsonArySize() {

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

      //length of JSON Location array
      int s = j.getInt("Location.size()");
      System.out.println("Array size of Location: " +s);
   }
}

輸出

更新於:2021 年 11 月 17 日

4K+ 瀏覽

開啟您的 職業 生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.