欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Gson解析泛型

程序员文章站 2022-07-02 19:41:06
1、简单对象我们传入对象Class来将JSON字符串转为对象 复杂的泛型需要构建TypeToken 复杂的泛型: 使用Gson来出来JSON,result为json字符串 ......

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