java.util.LinkedHashMap cannot be cast to xxx
程序员文章站
2022-03-31 11:40:15
java.util.LinkedHashMap cannot be cast to com.entity.Person 使用mybatis, resultMap映射的是实体类Person, 查询出来的结果是一个ArrayList,然后结果存放在一个ListObject的data属性中 ......
java.util.LinkedHashMap cannot be cast to com.entity.Person
使用mybatis, resultMap映射的是实体类Person, 查询出来的结果是一个ArrayList<Person>,然后结果存放在一个ListObject的data属性中,
存放结果的类
public class ListObject { private Object data; public Object getData() { return data; } public void setData(Object data) { this.data = data; } }
强制转换成List<Person> result = (List<Person>)result.getData();没有报错, 也拿到了数据,当使用for循环的时候报错 java.util.LinkedHashMap cannot be cast to com.entity.Person
ListObject result = method.query(name); List<Person> result = (List<Person>)result.getData();
for(Person per : result){ sourceList.add(per .getId()); }
解决方法:
导入 net.sf.json 类,使用JSONObject中的方法, 先将数据转成json字符串, 在转成实体对象
ListObject result = method.query(name); List<Person> result = (List<Person>)result.getData();
for(Object obj : result){
JSONObject jsonObject=JSONObject.fromObject(objectStr);
Person per = (Person)JSONObject.toBean(jsonObject, Person.class);
sourceList.add(per.getId());
}
主要就是两步
JSONObject jsonObject=JSONObject.fromObject(objectStr); // 将数据转成json字符串
Person per = (Person)JSONObject.toBean(jsonObject, Person.class); //将json转成需要的对象
推荐阅读
-
解决cannot be cast to javax.servlet.Filter 报错的问题
-
所有Intellij IDEA Cannot Resolve Symbol XXX问题的解决方法汇总
-
Set集合中的treeSet问题:cannot be cast to java.lang.Comparable;
-
SQL中使用sum()应该程序报错:java.math.BigDecimal cannot be cast to java.lang.Integer
-
java.util.LinkedHashMap cannot be cast to xxx
-
error while loading shared libraries: xxx: cannot open shared object file: No such file or directory
-
Property or field ‘XXX‘ cannot be found on null
-
The instance of entity type ‘xxx‘ cannot be tracked because another instance with the same key value
-
Ambiguous mapping found. Cannot map 'xxx' bean method
-
java报错大全java.lang.IllegalStateException: Ambiguous mapping Cannot map xxx