fastJson泛型如何转换

时间:2023-03-09 16:51:52
fastJson泛型如何转换

引子

  现在负责的业务 和 json 打交道比较多, 最近使用fastJson框架 json串转成泛型对象遇到了一个异常 :

java.lang.ClassCastException

还原下场景 :

模型Result<T>

public class Result<T> {

    private String msg;

    private List<T> module;

    public String getMsg() {
return msg;
} public void setMsg(String msg) {
this.msg = msg;
} public List<T> getModule() {
return module;
} public void setModule(List<T> module) {
this.module = module;
} }

为什么要使用泛型, 可以理解泛型可以接受任意类型, 有些代码是公用的, 如结果集, 不可能为每个具体结果定义一个模型, 比如 Result<User>、Result<Item>等。

public class User {

    private Long user_id;

    private String user_name;

    public User() {

    }

    public User(Long userId, String name) {
this.user_id = userId;
this.user_name = name;
} public Long getUser_id() {
return user_id;
} public void setUser_id(Long user_id) {
this.user_id = user_id;
} public String getUser_name() {
return user_name;
} public void setUser_name(String user_name) {
this.user_name = user_name;
} }

下面直接看下泛型的转换

    public static void main(String[] args) {

        Result<User> r = new Result<User>();

        r.setMsg("msg");

        List<User> users = new ArrayList<>();
users.add(new User(1L, "hehe"));
users.add(new User(2L, "haha")); r.setModule(users); String js = JSON.toJSONString(r); System.out.println(js); Result<User> obj = (Result<User>)JSON.parseObject(js, Result.class); User user = obj.getModule().get(0);
System.out.println(user);
}


结果 :

{"module":[{"user_id":1,"user_name":"hehe"},{"user_id":2,"user_name":"haha"}],"msg":"msg"}


Exception in thread "main" java.lang.ClassCastException: com.alibaba.fastjson.JSONObject cannot be cast to com.yuanmeng.json.User


at com.yuanmeng.json.fanxing.Client.main(Client.java:32)

 

采用fastjson框架的 TypeReference 即可将json串转成定义好的泛型对象

 
Result<User> obj = (Result<User>) JSON.parseObject(js, new TypeReference<Result<User>>(){});