如何使用Rest Assured从API响应中获取指定条件的字段值
Rest Assured条件筛选获取指定商家消费值
先补全你的API响应示例(修正后的完整JSON结构)
{ "data": { "content": [ { "merchantBrandName": "Netflix", "amount": { "absolute": 12.99, "currency": "USD" } }, { "merchantBrandName": "Amazon", "amount": { "absolute": 9.99, "currency": "USD" } } ] } }
实现方式
以下是两种在Rest Assured中实现条件查询的方法:
方法1:使用JsonPath的Groovy条件表达式
Rest Assured的JsonPath支持Groovy风格的筛选语法,直接通过表达式定位目标值:
// 从API响应初始化JsonPath对象 JsonPath js = response.jsonPath(); // 筛选并获取第一个匹配Netflix的absolute值 Double netflixAbsoluteValue = js.getDouble("data.content.findAll { it.merchantBrandName == 'Netflix' }.amount.absolute[0]"); // 输出结果 System.out.println("Netflix消费值:" + netflixAbsoluteValue);
findAll { it.merchantBrandName == 'Netflix' }:遍历content数组,筛选出merchantBrandName等于Netflix的元素.amount.absolute:提取筛选结果中嵌套的absolute字段[0]:取筛选结果列表的第一个元素(若确定只有一个Netflix条目)
如果需要处理多个匹配结果,可以先获取列表再遍历:
List<Double> netflixValues = js.getList("data.content.findAll { it.merchantBrandName == 'Netflix' }.amount.absolute"); if (!netflixValues.isEmpty()) { // 处理所有匹配值 }
方法2:结合Java Stream过滤
若更习惯Java常规写法,可以先将数组转为Map列表,再用Stream筛选:
JsonPath js = response.jsonPath(); // 获取content数组的所有元素为Map集合 List<Map<String, Object>> contentItems = js.getList("data.content"); // 筛选Netflix条目并提取absolute值 Optional<Double> netflixValue = contentItems.stream() .filter(item -> "Netflix".equals(item.get("merchantBrandName"))) .map(item -> { Map<String, Object> amountMap = (Map<String, Object>) item.get("amount"); return ((Number) amountMap.get("absolute")).doubleValue(); }) .findFirst(); // 安全获取结果 netflixValue.ifPresent(value -> System.out.println("Netflix消费值:" + value));
内容的提问来源于stack exchange,提问作者Adil Raza
相关产品推荐
相关产品推荐

