json轉對象json
public static <T> T json2Obj(String json, Class<T> cls) { Gson gson = new Gson(); return gson.fromJson(json, cls); }
json轉list objectui
不少例子根本都不是泛型的,還標榜泛型,真是誤導他人spa
能夠參考下面的方式來實現code
public static <T> List<T> json2ListObj(String json, Class<T> cls) { List reList = new ArrayList(); JsonElement jsonElement = new JsonParser().parse(json); JsonArray array = jsonElement.getAsJsonArray(); Iterator iterator = array.iterator(); Gson gson = new Gson(); while (iterator.hasNext()) { JsonElement json2 = (JsonElement) iterator.next(); T contact = gson.fromJson(json2, cls); //can set some values in contact, if required reList.add(contact); } return reList; }
不帶泛型的json轉list對象
gson.fromJson(json, new TypeToken<List<YourClass>>() {}.getType());