json转对象
public static <T> T json2Obj(String json, Class<T> cls) { Gson gson = new Gson(); return gson.fromJson(json, cls); }
json转list object
很多例子根本都不是泛型的,还标榜泛型,真是误导他人
可以参考下面的方式来实现
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());