class java.util.LinkedHashMap cannot be cast to class com,XXXXX is in unnamed module of loader org.springframework.boot.loader.launch.LaunchedClassLoader @54bedef2

场景一:使用 RestTemplate 调用接口(最常见)

// ❌ 错误写法:泛型擦除,RestTemplate 不知道 List 里面应该是

CoeffVo List<CoeffVo> result = restTemplate.getForObject(url, List.class);

正确做法:使用 ParameterizedTypeReference

/ 1. 定义类型引用,保留泛型信息
ParameterizedTypeReference<List<CoeffVo>> typeRef = new ParameterizedTypeReference<List<CoeffVo>>() {};

// 2. 使用 exchange 方法
ResponseEntity<List<CoeffVo>> response = restTemplate.exchange(
    url, 
    HttpMethod.GET, 
    null, 
    typeRef
);

// 3. 获取结果,此时列表中的元素已经是 CoeffVo 对象
List<CoeffVo> coeffList = response.getBody();

场景二:使用 Feign 客户端

如果 Feign 接口返回的是 Object 或 Map,【应该显示的定义明确的返回类型,不要在调用的时候强转】或者配置不当,也可能出现此问题。

@FeignClient(name = "plm-service")
public interface PlmClient {
    // 确保返回类型直接写具体的 VO 类或 List<VO>
    @GetMapping("/cff/list")
    Result<List<CfVo>> getCList();
}

注意:确保你的 Feign 配置中使用了正确的 Decoder(如 JacksonDecoder),且 Result 包装类也是泛型明确的。

场景三:手动解析 JSON 字符串

如果你从 Redis 或消息队列拿到的是 JSON 字符串,手动转对象时出错。

正确做法:指定目标 Class

import com.fasterxml.jackson.databind.ObjectMapper;

ObjectMapper mapper = new ObjectMapper();

// 直接指定要转换成的目标类型
CoeffVo vo = mapper.readValue(jsonStr, CoeffVo.class);

// 如果是列表
List<CoeffVo> list = mapper.readValue(
    jsonStr, 
    new TypeReference<List<CoeffVo>>() {}
);

 

 

posted @ 2026-07-09 15:44  狗艳艳花  阅读(19)  评论(0)    收藏  举报