亲宝软件园·资讯

展开

fastjson 泛型转换 解决fastjson泛型转换报错的解决办法

旷野历程 人气:5

错误信息

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());}
}

加载全部内容

相关教程
猜你喜欢
用户评论