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