Solve the problem of java.util.linkedhashmap cannot be cast to entity class
Background description
When learning about grain mall, openfeign is used for remote call, because an interface returns R < List<ยท Object>> Type of data, using list <Object> When receiving data, the java.util.linkedhashmap cannot be cast to XXX data conversion exception error occurs. It can be seen that the remote call will convert the data to be converted to LinkedHashMap, but it will not work to convert it to the desired data type.
Solution one
Use typereference in fastjson tool provided by Alibaba to transform.
We add SetData () and GetData () methods to R. when getting data, we use typereference class to indicate the data type. Then convert the map to the JSON string, and then convert the JSON string to the data type we want.
public class R extends HashMap<String, Object> {
private static final long serialVersionUID = 1L;
public R setData(Object data){
put("data",data);
return this;
}
//Reversal with fastjson
public <T> T getData(TypeReference<T> typeReference){
Object data = get("data");//Default is map type
if(Objects.isNull(data)){
return null;
}
String s = JSON.toJSONString(data);
T t = JSON.parseObject("",typeReference);
return t;
}
Caller
R r = wareFeignService.getSkusHasStock(skuIdList);//Remote calls
TypeReference<List<SkuHasStockVo>> typeReference = new TypeReference<List<SkuHasStockVo>>() {
};// Declare the internal class, specifying the type
List<SkuHasStockVo> data = r.getData(typeReference);//get data for remote calls
reflection
This problem also occurred when using resttemplate remote call before. This problem was solved before, and the solution steps were not recorded. This time, the solution steps will be recorded to prevent the next step.
Supplementary solution 2
Recently, when reviewing the previous project code, I found a similar problem when using resttemplate remote call mentioned in my thinking. The solution at the time was this.
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
//remote call, return the specified collection, but this collection can not be used directly, because he is a LinkedHashMap.
List<InnerControl> remoteList = restTemplate.getForObject("url", List.class);
remoteList = transToList(remoteList);// After the conversion, you will be able to use this collection normally.
// Define a method to convert the LinkedHashMap type to the data type we want
private List<InnerControl> transToList(List<InnerControl> list){
String jsonStr = JSON.toJSONString(list);//still use the json conversion tool provided by alibaba.
return JSONObject.parseArray(jsonStr, InnerControl.class);
}