解决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 = JSONString(resultSetDTO);
System.out.println(jsonString);
ResultSetDTO<XsyUserDO> resultSet = JSON.parseObject(jsonString, ResultSetDTO.class);
List<UserDO> records = Records();
// 转换是报异常
for (UserDO user : records) {
System.out.Name());
}
}
debuge 调试时发现Records();返回的是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.String("records"), UserDO.class);
for (UserDO user : records) {
System.out.Name());
}
// ⽅法⼆
ResultSetDTO<XsyUserDO> resultSet = JSON.parseObject(jsonString, ResultSetDTO.class);
List<UserDO> records = JSONObject.Records().toString(), UserDO.class);
for (UserDO user : records) {
System.out.Name());
}
object to// ⽅法三
ResultSetDTO<XsyUserDO> resultSet = JSON.parseObject(jsonString, new TypeReference<ResultSetDTO<UserDO>>(){});
List<UserDO> records = Records();
for (UserDO user : records){
System.out.Name());}
}
到此这篇关于解决fastjson泛型转换报错的解决⽅法的⽂章就介绍到这了,更多相关fastjson 泛型转换内容请搜索以前的⽂章或继续浏览下⾯的相关⽂章希望⼤家以后多多⽀持!

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。