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

使用RestTemplate时遭遇java.lang.ClassCastException问题求助

解决java.lang.ClassCastException: LinkedHashMap无法转换为Employee的问题

问题原因

你遇到的类型转换异常,核心是Java泛型擦除机制导致的RestTemplate反序列化错误:
当调用restTemplate.getForObject("http://localhost:3232/survey", List.class)时,泛型信息在运行时被擦除,RestTemplate无法识别List的泛型参数是Employee,只能将JSON数组中的每个对象默认反序列化为LinkedHashMap。后续你将这个List<LinkedHashMap>强转为List<Employee>,遍历的时候试图把LinkedHashMap强制转换为Employee,就会抛出ClassCastException。

解决方案

提供两种可靠的修复方式:

方式一:使用ParameterizedTypeReference保留泛型信息

通过RestTemplate.exchange方法配合ParameterizedTypeReference,明确告诉RestTemplate要反序列化的泛型类型:

@Service
public class EmployeeService {

    public List<Employee> getListEmployee() {
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<List<Employee>> response = restTemplate.exchange(
                "http://localhost:3232/survey",
                HttpMethod.GET,
                null,
                new ParameterizedTypeReference<List<Employee>>() {}
        );
        return response.getBody();
    }

    // 其余方法保持不变
}

方式二:先反序列化为数组再转成List

直接将JSON反序列化为Employee数组,再转换为List,规避泛型擦除的影响:

@Service
public class EmployeeService {

    public List<Employee> getListEmployee() {
        RestTemplate restTemplate = new RestTemplate();
        Employee[] employeeArray = restTemplate.getForObject("http://localhost:3232/survey", Employee[].class);
        // Arrays.asList返回不可修改的List,若需要可修改集合,改用new ArrayList<>(Arrays.asList(employeeArray))
        return Arrays.asList(employeeArray);
    }

    // 其余方法保持不变
}

额外注意事项

确保Employee类的字段和接口返回的JSON字段名称匹配:
如果JSON字段采用驼峰命名(如employeeId),而你的类字段是EmployeeID,需要通过@JsonProperty注解指定映射关系,例如:

@JsonProperty("employeeId")
private String EmployeeID;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 18:15:05