如何在Rest Assured中解析JSON响应并获取响应中的特定字段?


我们可以使用Rest Assured解析JSON响应并从响应中获取特定字段。这是借助JSONPath类完成的。要解析JSON响应,我们首先必须将响应转换为字符串。

要获取响应,我们需要使用这些方法 - Response.body或Response.getBody。这两个方法都是Response接口的一部分。

获得响应后,它将借助asString方法转换为字符串。此方法是ResponseBody接口的一部分。然后,我们将借助jsonPath方法从响应主体中获取JSON表示。

我们将首先通过Postman向模拟API URL发送GET请求并查看响应。

示例

使用Rest Assured,我们将获取Course、id和Price字段的值。

import org.testng.annotations.Test;
import static io.restassured.RestAssured.*;
import io.restassured.RestAssured;
import io.restassured.path.json.JsonPath;
import io.restassured.response.Response;
import io.restassured.response.ResponseBody;
import io.restassured.specification.RequestSpecification;
public class NewTest {
   @Test
   void responseExtract() {
      //base URI with Rest Assured class
      RestAssured.baseURI = "https://run.mocky.io/v3";
      //input details
      RequestSpecification h = RestAssured.given();
      //get response
      Response r = h.get("/e3f5da9c-6692-48c5-8dfe-9c3348cfd5c7");
      //Response body
      ResponseBody bdy = r.getBody();
      //convert response body to string
      String b = bdy.asString();
      //JSON Representation from Response Body
      JsonPath j = r.jsonPath();
      //Get value of Location Key
      String l = j.get("Course");
      System.out.println("Course name: " + l);
      String m = j.get("id");
      System.out.println("Course Id: " + m);
      String n = j.get("Price");
      System.out.println("Course Price: " + n);
   }
}

输出

更新于:2021年11月17日

10K+ 浏览量

开启你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.