错误信息
Exception in thread "main" java.lang.ClassCastException: com.alibaba.fastjson.JSONObject cannot be cast to com.xh.demo.UserDO
泛性类
@Data
public class ResultSetDTO {
private Integer totalSize;
private Integer count;
private List records;
}
实体类
@Data
public class UserDO {
private String id;
private String name;
}
Demo测试
public class AppDemo {
public static void main(String[] args) {
ResultSetDTO resultSetDTO = new ResultSetDTO();
resultSetDTO.setTotalSize(10);
resultSetDTO.setCount(10);
List list = new ArrayList<>();
UserDO userDO = null;
for (int i = 10000; i < 10003; i++) {
userDO = new UserDO();
userDO.setId(i + "");
userDO.setName("TEST_" + i);
list.add(userDO);
}
resultSetDTO.setRecords(list);
String jsonString = JSON.toJSONString(resultSetDTO);
System.out.println(jsonString);
ResultSetDTO resultSet = JSON.parseObject(jsonString, ResultSetDTO.class);
List records = resultSet.getRecords();
// 转换是报异常
for (UserDO user : records) {
System.out.println(user.getName());
}
}
debuge 调试时发现 resultSet.getRecords(); 返回的是 ArrayList 类型,不是 ArrayList 类型。由于类型引用必须强制指定目标对象,因此违背了 FastJson 规范,所以报:Exception in thread "main" java.lang.ClassCastException: com.alibaba.fastjson.JSONObject cannot be cast to com.xh.demo.UserDO。
解决方法
// 方法一
JSONObject parseObject = JSON.parseObject(jsonString);
List records = JSON.parseArray(parseObject.getString("records"), UserDO.class);
for (UserDO user : records) {
System.out.println(user.getName());
}
// 方法二
ResultSetDTO resultSet = JSON.parseObject(jsonString, ResultSetDTO.class);
List records = JSONObject.parseArray(resultSet.getRecords().toString(), UserDO.class);
for (UserDO user : records) {
System.out.println(user.getName());
}
// 方法三
ResultSetDTO resultSet = JSON.parseObject(jsonString, new TypeReference>(){});
List records = resultSet.getRecords();
for (UserDO user : records){
System.out.println(user.getName());}
}
到此这篇关于解决fastjson泛型转换报错的解决方法的文章就介绍到这了,更多相关fastjson 泛型转换内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!