1、报错原因
在获取json数据转换为list类型以后,我以为是可以直接使用的,结果在使用中报错“java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to ×××”,搜索后发现是在转换成list时,list类型是LinkedHashMap,而不是我需要的List,Jackson在转换时按照标准行为将数据以List 返回,而不是作为 List 返回,但是我需要list中类型是我自定义的对象;
2、解决办法
导入依赖:
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
类型转换:
List<T> records = result.getData().getList();
//使用ObjectMapper解决
//创建一个ObjectMapper
ObjectMapper mapper = new ObjectMapper();
//OperLog就是需要的类型对象
List<OperLog> operLogs= mapper.convertValue(records, new TypeReference<List<OperLog>>() {});