Rest Assured API新手求助:如何从JSON响应中获取全部记录
用Rest Assured提取JSON响应中的全部记录
嘿,我来帮你搞定这个问题!从你给出的JSON结构来看,所有员工电话记录都嵌套在顶级的Result数组里,用Rest Assured可以轻松提取整个数组,下面分两种常用方法来实现:
方法一:用Map列表接收(快速上手,无需额外类)
这种方式适合快速验证或者临时处理,不需要提前定义实体类:
// 1. 发送请求并获取响应,先验证状态码匹配你的JSON中的200 Response response = given() .when() .get("你的API接口地址") // 替换成实际接口地址 .then() .statusCode(200) .extract() .response(); // 2. 用JsonPath定位到Result数组,提取所有记录 JsonPath jsonPath = response.jsonPath(); List<Map<String, Object>> allPhoneRecords = jsonPath.getList("Result"); // 3. 遍历列表处理每条记录 for (Map<String, Object> record : allPhoneRecords) { String employeeId = (String) record.get("EmployeeId"); String phoneType = (String) record.get("PhoneTypeDescription"); String phoneNumber = (String) record.get("PhoneNumber"); // 这里可以根据需求做打印、存储或者其他逻辑 System.out.printf("员工ID:%s | 电话类型:%s | 号码:%s%n", employeeId, phoneType, phoneNumber); }
方法二:用POJO实体类映射(类型安全,推荐长期使用)
如果需要频繁处理这类数据,定义一个对应结构的POJO类会更优雅,避免类型转换的麻烦:
第一步:创建POJO类
public class EmployeePhone { // 字段名要和JSON中的键完全一致,或者用@JsonProperty注解指定映射关系 private String EmployeeId; private String PhoneTypeDescription; private String PhoneNumber; // 添加getter和setter方法,或者用Lombok的@Data注解自动生成 public String getEmployeeId() { return EmployeeId; } public void setEmployeeId(String employeeId) { EmployeeId = employeeId; } public String getPhoneTypeDescription() { return PhoneTypeDescription; } public void setPhoneTypeDescription(String phoneTypeDescription) { PhoneTypeDescription = phoneTypeDescription; } public String getPhoneNumber() { return PhoneNumber; } public void setPhoneNumber(String phoneNumber) { PhoneNumber = phoneNumber; } }
第二步:提取并映射为实体类列表
// 同样先获取响应 Response response = given() .when() .get("你的API接口地址") .then() .statusCode(200) .extract() .response(); // 直接将Result数组映射为EmployeePhone对象列表 JsonPath jsonPath = response.jsonPath(); List<EmployeePhone> allPhoneRecords = jsonPath.getList("Result", EmployeePhone.class); // 遍历处理,无需强转,类型更安全 for (EmployeePhone record : allPhoneRecords) { System.out.printf("员工ID:%s | 电话类型:%s | 号码:%s%n", record.getEmployeeId(), record.getPhoneTypeDescription(), record.getPhoneNumber()); }
关键说明
- 核心路径是
"Result":因为你的JSON响应中,所有记录都在顶级的Result数组下,Rest Assured的JsonPath会直接定位到这个数组并返回所有元素。 - 如果JSON有嵌套结构,路径需要调整(比如
"data.Result"),但你的结构很直接,直接用"Result"就够了。
内容的提问来源于stack exchange,提问作者Anton
相关产品推荐
相关产品推荐

