如何使用RestAssured获取GET请求返回的首个学生ID
使用RestAssured获取第一个学生的ID
要从返回的学生列表JSON数组中提取第一个学生的ID,你可以借助RestAssured内置的JSONPath功能实现,以下是具体实现方式:
方式一:分步解析响应
import io.restassured.RestAssured; import io.restassured.path.json.JsonPath; public class StudentIdExtractor { public static void main(String[] args) { // 发送GET请求,替换为你的实际接口URL String responseBody = RestAssured.get("https://your-api-url/students") .asString(); // 初始化JsonPath解析器 JsonPath jsonPath = new JsonPath(responseBody); // 提取第一个学生的ID(数组索引从0开始) int firstStudentId = jsonPath.getInt("[0].id"); // 输出结果 System.out.println("第一个学生的ID:" + firstStudentId); } }
方式二:链式调用简化写法
如果不需要单独保存响应体,可以直接通过链式调用完成提取:
import io.restassured.RestAssured; public class StudentIdExtractor { public static void main(String[] args) { int firstStudentId = RestAssured.get("https://your-api-url/students") .jsonPath() .getInt("[0].id"); System.out.println("第一个学生的ID:" + firstStudentId); } }
补充:断言验证ID值
如果需要同时验证第一个学生的ID是否符合预期,可以结合断言使用:
import static org.hamcrest.Matchers.equalTo; import io.restassured.RestAssured; public class StudentIdAssertion { public static void main(String[] args) { RestAssured.get("https://your-api-url/students") .then() .assertThat() .body("[0].id", equalTo(14114)); } }
核心逻辑说明:
[0]定位到JSON数组的第一个元素(JSON数组索引从0开始).id提取该元素下的id字段值
内容的提问来源于stack exchange,提问作者Developer
相关产品推荐
相关产品推荐

