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