如何使用gson.fromJson反序列化泛型类型数组
public class Cache<T> {
public void M(String json) {
JsonArray ja = (JsonArray) new JsonParser().parse(json);
Gson gson = new GsonBuilder().create();
T[] items = gson.fromJson(ja, ?);
}
}
这不起作用
Type t = new TypeToken<ArrayList<T>>() {}.getType();
T[] items = gson.fromJson(ja, t);
T[] items = gson.fromJson(ja, T[].class);
T[] items = gson.fromJson(ja, new T[].getClass());
答案 0 :(得分:0)
T[] array = (T[]) Array.newInstance(clazz, 0);
T[] result = gson.fromJson(jsonString, (Type) array.getClass());
List<T> resultList = Arrays.asList(result);