[Turn] fastjson generic class conversion

Introduction
  Now I am in charge of dealing with json a lot. Recently, I encountered an exception using the fastJson framework to convert json strings into generic objects:

java.lang.ClassCastException



Restore the next scenario:

model Result<T>

copy code
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;
    }
   
   
}

Why use generics? It can be understood that generics can accept any type. Some codes are common, such as result sets. It is impossible to define a model for each specific result, such as Result<User>, Result<Item>, etc. 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);
    }
Copy Code
Copy Code
Copy Code
Result :
{"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)


Copy code


Use the TypeReference of the fastjson framework to convert the json string into a defined generic object


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


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326217483&siteId=291194637