You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 15:40:28