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

如何用Rest Assured验证JSON中指定键值对的产品是否存在?

解决Rest Assured中按名称+价格断言产品存在的问题

问题背景

接口返回的JSON响应格式如下:

{"products": [{"name": "toy1","price": 99},{"name": "toy2","price": 88},{"name": "toy3","price": 99}]}

需要根据名称和价格的组合判断指定产品是否存在,预期断言结果:

namepriceisExist
toy199true
toy299false
toy288true
sometoy99false

此前尝试过转Map列表(实现繁琐)、使用JsonPath包(受限无法使用)、扁平化JSON(出现键冲突),均未解决问题。

解决方案

直接利用Rest Assured自带的响应解析能力,结合Java Stream流操作实现,无需额外依赖:

代码实现

import io.restassured.response.Response;
import java.util.List;
import java.util.Map;

// 假设已获取接口响应对象response
Response response = ...;

// 提取products列表
List<Map<String, Object>> productsList = response.jsonPath().getList("products");

// 判断产品是否存在的方法
public boolean isProductPresent(String targetName, int targetPrice) {
    return productsList.stream()
            .anyMatch(product -> 
                targetName.equals(product.get("name")) 
                && targetPrice == (int) product.get("price")
            );
}

// 执行断言验证
assert isProductPresent("toy1", 99) == true;
assert isProductPresent("toy2", 99) == false;
assert isProductPresent("toy2", 88) == true;
assert isProductPresent("sometoy", 99) == false;

方案说明

  • 用Rest Assured内置的jsonPath().getList()直接提取products数组为Map列表,省去手动解析JSON的冗余步骤
  • 通过Stream的anyMatch()方法,一次遍历即可完成名称+价格的组合匹配判断,代码简洁高效
  • 无需引入额外依赖或做JSON扁平化处理,规避了之前遇到的键冲突、依赖受限等问题

内容的提问来源于stack exchange,提问作者shadowless

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 17:53:10