Spring WebClient动态Schema响应反序列化异常解决方法
解决Spring WebClient处理不一致JSON响应的问题
问题核心是外部API返回的JSON结构不统一:有数据时返回对象,无数据时返回空数组,直接反序列化为Map<String, UUID>会触发类型不匹配的解码异常。以下是直接有效的修改方案:
修改后的代码
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.core.type.TypeReference; import org.springframework.web.reactive.function.client.WebClient; import java.util.Collections; import java.util.Map; import java.util.UUID; import java.util.List; public Map<String, UUID> getIdsByDisplayNames(List<String> displayNames) { ObjectMapper objectMapper = new ObjectMapper(); JsonNode responseNode = webClient.get() .uri(uriBuilder -> { uriBuilder.path("/api/display-names/account-ids"); for (String displayName : displayNames) { uriBuilder.queryParam("displayName[]", displayName); } return uriBuilder.build(); }) .retrieve() .bodyToMono(JsonNode.class) .block(); if (responseNode == null) { return Collections.emptyMap(); } if (responseNode.isObject()) { try { return objectMapper.convertValue(responseNode, new TypeReference<Map<String, UUID>>() {}); } catch (IllegalArgumentException e) { // 处理字段类型不匹配等转换失败场景 return Collections.emptyMap(); } } else if (responseNode.isArray() && responseNode.isEmpty()) { return Collections.emptyMap(); } else { // 处理其他意外的JSON结构 return Collections.emptyMap(); } }
关键逻辑说明
- 先解析为通用JSON节点:将响应体反序列化为
JsonNode,这是Jackson提供的通用类型,能兼容对象、数组等所有JSON结构,避免直接转Map时的类型冲突。 - 分类型处理响应:
- 若为对象节点:使用
ObjectMapper.convertValue()将其转换为目标Map<String, UUID>类型 - 若为空数组节点:直接返回空Map,符合业务逻辑中“无数据”的场景
- 若为对象节点:使用
- 异常与边界处理:增加了空响应、转换失败、意外结构的处理,保证方法的健壮性
内容的提问来源于stack exchange,提问作者Kirill Gnilov
相关产品推荐
相关产品推荐

