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

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();
    }
}

关键逻辑说明

  1. 先解析为通用JSON节点:将响应体反序列化为JsonNode,这是Jackson提供的通用类型,能兼容对象、数组等所有JSON结构,避免直接转Map时的类型冲突。
  2. 分类型处理响应:
    • 若为对象节点:使用ObjectMapper.convertValue()将其转换为目标Map<String, UUID>类型
    • 若为空数组节点:直接返回空Map,符合业务逻辑中“无数据”的场景
  3. 异常与边界处理:增加了空响应、转换失败、意外结构的处理,保证方法的健壮性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 22:42:39