如何使用 Rest Assured 遍歷和訪問 JSON 陣列元素?
我們可以使用 Rest Assured 遍歷和訪問 JSON 陣列元素。首先,我們將獲取一個 JSON 格式的響應主體。然後將其轉換為字串。
要獲取 JSON 陣列大小,我們必須對 JSON 陣列使用 size 方法。然後引入一個迴圈,遍歷到陣列大小。我們將透過 Postman 對一個模擬 API 傳送 GET 請求,並觀察響應。
使用 Rest Assured,讓我們獲取具有 State 和 zip 值的 Location 欄位值。它們是 JSON 陣列 - Location 的一部分。
示例
程式碼實現
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 jsonIterateArr() { //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"); String zip = j.getString("Location["+i+"].zip"); System.out.println(state); System.out.println(zip); } } }
輸出
廣告