【问题标题】:Parsing Json to List of Items with generic field with Gson使用 Gson 将 Json 解析为具有通用字段的项目列表
【发布时间】:2014-07-01 08:06:49
【问题描述】:
public class OwnCollection<T>{
    private int size;
    private List<ResponseItem<T>> data;
}

public class ResponseItem<T>{
    private String path;
    private String key;
    private T value;
}

public class Query{
    public <T> OwnCollection<T>  getParsedCollection( ... ){
        String json = ...; //some unimportant calls where I get an valid Json to parse
        return Result.<T>parseToGenericCollection(json);
    }
}

public class Result{
    public static <T> OwnCollection<T> parseToGenericCollection(String result){
        Type type = new TypeToken<OwnCollection<T>>() {}.getType();
        //GsonUtil is a class where I get an Instance Gson, nothing more.
        return GsonUtil.getInstance().fromJson(result, type);
    }
}

现在我怎么称呼它:

OwnCollection<Game> gc = new Query().<Game>getParsedCollection( ... );

结果我想,我会得到一个OwnCollection 和一个List&lt;ResponseItem&gt;,其中一个响应项包含Game 类的字段。 Json 非常好,没有解析错误,现在唯一的问题是当我尝试获取一个 Game 项目并调用方法时出现此错误:

Exception in thread "main" java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to at.da.example.Game

【问题讨论】:

    标签: java json generics gson


    【解决方案1】:

    这样不行,因为下面的代码

    OwnCollection<Game> gc = new Query().<Game>getParsedCollection( ... );
    

    实际上不会在getParsedCollection() 中传递Game。这里的&lt;Game&gt; 只告诉编译器getParsedCollection() 应该返回OwnCollection&lt;Game&gt;,但getParsedCollection()(和parseToGenericCollection())内部的T 仍然被擦除,因此TypeToken 无法帮助您捕获它的值。

    您需要将Game.class 作为参数传递

    public <T> OwnCollection<T> getParsedCollection(Class<T> elementType) { ... }
    ...
    OwnCollection<Game> gc = new Query().getParsedCollection(Game.class);
    

    然后使用TypeTokenOwnCollectionTelementType链接如下:

    Type type = new TypeToken<OwnCollection<T>>() {}
        .where(new TypeParameter<T>() {}, elementType)
        .getType();
    

    请注意,此代码使用 TypeToken from Guava,因为来自 Gson 的 TypeToken 不支持此功能。

    【讨论】:

    • 虽然我不会这么快得到答案 - 我要去测试它。谢谢
    • 你我的朋友真棒!完美运行!现在阅读此内容的每个人-> 支持它!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-14
    • 2013-03-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多