相关疑难解决方法(0)

如何使用Google GSON将JSON数组反序列化为泛型类型的集合?

我正在编写一些代码,用于从网站中检索资源.它看起来像这样:

public Collection<Project> getProjects() {
        String json = getJsonData(methods.get(Project.class)); //Gets a json list, ie [1, 2, 3, 4]
        Gson gson = new Gson();
        Type collectionType = new TypeToken<Collection<Project>>() {}.getType();
        return gson.fromJson(json, collectionType);
    }
Run Code Online (Sandbox Code Playgroud)

所以我很自然地尝试使用Java泛型来抽象它.

/*
     * Deserialize a json list and return a collection of the given type.
     * 
     * Example usage: getData(AccountQuota.class) -> Collection<AccountQuota>
     */
    @SuppressWarnings("unchecked")
    public <T> Collection<T> getData(Class<T> cls) {
        String json = getJsonData(methods.get(cls)); //Gets a json list, ie [1, 2, 3, 4]
        Gson gson = new …
Run Code Online (Sandbox Code Playgroud)

java generics gson

11
推荐指数
3
解决办法
3万
查看次数

标签 统计

generics ×1

gson ×1

java ×1