Gson解析泛型


1、簡單對象我們傳入對象Class來將JSON字符串轉為對象

 private static <T> T fromJson(String result, Class<T> classOfT) {
        if (result == null) {
            return null;
        }
        Gson gson = new Gson();
        return gson.fromJson(result, classOfT);
    }

復雜的泛型需要構建TypeToken

復雜的泛型:

import java.util.List;

public class PageList<T> {
    public int Total;

    public int NoReadCount;

    public List<T> Rows;
}

使用Gson來出來JSON,result為json字符串

 Gson gson = new Gson();
 Type type = new TypeToken<PageList<Message>>() {}.getType();
 final PageList<Message> pageList = gson.fromJson(result, type);

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM