如何使用WebClient过滤API响应仅保留systemId=100的关联客户数据
WebClient响应过滤实现方案
你可以在响应反序列化为CuCoPerson实体后,通过Reactor的map操作符对实体内部的relatedCustomers列表做过滤,仅保留systemId=100的条目,不需要修改下游接口的请求逻辑。
前提确认
确保你的CustomerRelation类存在systemId字段,由于你使用了Lombok的@Data注解,会自动生成对应getter/setter方法,无需额外编写。
修改后的完整接口代码
import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; @GetMapping("/getCucoId/{cucoId}") public Mono<CuCoPerson> getCucoRelationById(@PathVariable Integer cucoId) { // 提示:WebClient建议声明为全局单例Bean注入使用,不要每次请求新建实例,避免连接资源浪费 WebClient webClient = WebClient.create(); return webClient.get() .uri(GET_RELATION_BY_ID + cucoId) .header("Accept", "application/json") .header("Authorization", "Bearer eyJraWQiOi.....") .retrieve() .bodyToMono(CuCoPerson.class) // 新增过滤处理逻辑 .map(person -> { // 空值兜底,避免下游返回null列表时触发空指针 List<CustomerRelation> validRelations = Optional.ofNullable(person.getRelatedCustomers()) .orElse(Collections.emptyList()); // 过滤仅保留systemId=100的条目 List<CustomerRelation> filteredRelations = validRelations.stream() .filter(relation -> Integer.valueOf(100).equals(relation.getSystemId())) .collect(Collectors.toList()); // 将过滤后的列表设置回实体 person.setRelatedCustomers(filteredRelations); return person; }); }
关键说明
- 过滤判断使用
Integer.valueOf(100).equals()而非==,可以避免Integer拆箱时的空指针异常,同时规避Integer缓存范围外的值比较失效问题。 - 加了
Optional空值处理,即使下游返回的relatedCustomers为null,接口也不会抛出空指针,会返回空列表。 - 如果你不希望修改原始反序列化得到的
CuCoPerson对象,也可以在map操作中新建一个CuCoPerson实例,传入原有cucoID和过滤后的列表,避免对象修改的副作用。
最终返回效果
基于你给出的原始下游响应,过滤后接口返回的JSON结构如下:
{ "cucoID": 100288298, "relatedCustomers": [ { "customerId": "F6305957", "systemId": 100 } ] }
内容的提问来源于stack exchange,提问作者DiegoMG
相关产品推荐
相关产品推荐

