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