FastJson反序列化问题
前言
项目中序列化一直用的FastJson、今天在序列化提示 com.alibaba.fastjson.JSONObject cannot be cast to com.example.snailthinkdemo.pojo.OrmUserPO
,究竟是道德的沦丧还是,FashJson 的泯灭,请各位看官老爷和我一探究竟。
发现问题
- 伪代码如下
List<OrmUserPO> studentList = new ArrayList<OrmUserPO>();
OrmUserPO student1 = new OrmUserPO();
student1.setId(Long.valueOf("1"));
student1.setName("张三");
List<String> resultNumbers = new ArrayList<String>();
resultNumbers.add("12");
resultNumbers.add("23");
student1.setNameList(resultNumbers);
OrmUserPO student2 = new OrmUserPO();
student2.setName("王二");
student2.setId(Long.valueOf("2"));
List<String> resultNumbers2 = new ArrayList<String>();
resultNumbers2.add("45");
resultNumbers2.add("56");
student2.setNameList(resultNumbers);
studentList.add(student1);
studentList.add(student2);
Map<String, Object> map = new HashMap<String, Object>();
map.put("count", 2);
map.put("userList", studentList);
String json = JSON.toJSONString(map, true);
反序列化后Json字符串如下
可以看见,这个json字符串内有一个内置的List
出现com.alibaba.fastjson.JSONObject cannot be cast to com.example.snailthinkdemo.pojo.OrmUserPO
异常是如下代码
HashMap parseMap = JSON.parseObject(json, HashMap.class);
List<OrmUserPO> userList2 = (List<OrmUserPO>) parseMap.get("userList");
for(OrmUserPO userPO : userList2){ // Exception
System.out.println(userPO.getId() + " ");
}
userList2
实际是JSONObject
解决问题
//反序列化List
List<OrmUserPO> studentList1 = JSON.parseArray(JSON.parseObject(json).getString("userList"), OrmUserPO.class);