如何使用 Rest Assured 获取嵌套 JSON 中的 JSON 数组字段?
rest assureddynamic programmingprogramming更新于 2025/4/5 16:22:17
我们可以使用 Rest Assured 获取嵌套 JSON 中的 JSON 数组字段。首先,我们将从请求中获取 JSON 格式的响应主体。然后将其转换为字符串。
最后,要获取特定的数组值,我们将使用数组索引,后跟字段名称。我们将通过 Postman 在模拟 API 上发送 GET 请求,并观察响应。
使用 Rest Assured,让我们获取第二个 zip 字段的值,其值为 49086。它是 Location 数组中第二个 JSON 的一部分。我们将通过遍历路径获取第二个 zip 的值 - Location[1].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"; //从 GET 请求获取响应 Response res = given() .when() .get("/8ec8f4f7-8e68-4f4b-ad18-4f0940d40bb7"); //将 JSON 转换为字符串 JsonPath j = new JsonPath(res.asString()); //第二个位置数组的 Zip String zip = j.getString("Location[1].zip"); System.out.println("Zip for 2nd Location array: " + zip); } }