google.gson.fromJson其中classOfT是通用数组

时间:2015-09-30 12:44:37

标签: java android json gson

如何使用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());

1 个答案:

答案 0 :(得分:0)

T[] array = (T[]) Array.newInstance(clazz, 0);
T[] result = gson.fromJson(jsonString, (Type) array.getClass());
List<T> resultList = Arrays.asList(result);