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);
}
Read More:
- [Solved] Java.lang.ClassCastException: [Ljava.lang.Long; cannot be cast to java.util.List
- [How to Solve Error]java.util.Date cannot be cast to java.sql.Date
- [Solved] Scala error: type mismatch; found : java.util.List[?0] required: java.util.List[B]
- [Solved] Failed to convert value of type ‘java.lang.String‘ to required type ‘java.util.Date‘;
- When the database table field is set to self incrementing, use the entity class to insert or update the data to solve the error (Hibernate Framework)
- [Solved] Failed to instantiate java.util.List using constructor NO_CONSTRUCTOR with arguments
- Java learning unreported exception java.io.IOException ; must be caught or declared to be thrown
- Mybatis Error: Error instantiating class bakou.entity.Person with invalid types () or value)
- [Solved] JSON parse error: Cannot deserialize instance of `java.util.ArrayList<..> out of START_OBJECT token;
- Java uses class array to report error Exception in thread “main” java.lang.NullPointerException solution
- [Solved] java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Tomcat].StandardHost[localhost].StandardContext[]]
- Springboot integrates Redis annotation and access error: java.io.NotSerializableException: com.demo.entity.MemberEntity
- [How to Solve]Repeated column in mapping for entity,should be mapped with insert=“false“ update=“false“
- Java will convert Excel to list set or JSON, export excel file to local, excel import and export, easyexcel tool class
- How to Fix Error Caused by: java.util.MissingResourceException: Can‘t find bundle for base name xxx, locale zh_CN
- How to Solve Java Runtime (class file version 53.0)ERROR
- Java error: unable to find or load main class (package name in source file)
- Solve the use of declaration transactions in spring java.lang.NoClassDefFoundError: org/aspectj/util/PartialOrder$PartialComparable
- java.util.zip.zipexception: error in opening zip file
- [Solved] Hbase-shell 2.x Error: Unhandled Java exception: java.lang.IncompatibleClassChangeError: Found class jline.Terminal…