fastJson泛型如何轉換

 引子

  如今負責的業務 和 json 打交道比較多, 最近使用fastJson框架 json串轉成泛型對象遇到了一個異常 :java

java.lang.ClassCastExceptionjson

 

還原下場景 : 框架

模型Result<T>this

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>等。spa

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

}

下面直接看下泛型的轉換code

    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.Userblog

 
 

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

 

 

採用fastjson框架的 TypeReference 便可將json串轉成定義好的泛型對象it

 
Result<User> obj = (Result<User>) JSON.parseObject(js, new TypeReference<Result<User>>(){});
相關文章
相關標籤/搜索