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

 

posted @ 2018-08-07 14:37  _York  阅读(6754)  评论(0编辑  收藏  举报