编程语言
首页 > 编程语言> > 传递parramaters的泛型方法 – java.lang.ClassCastException:com.google.gson.internal.LinkedTreeMap

传递parramaters的泛型方法 – java.lang.ClassCastException:com.google.gson.internal.LinkedTreeMap

作者:互联网

我有一个简单的泛型类:

public class OwnedCollection<T extends BaseObject> extends BaseObject {

    private String playerId;
    private List<T> collection;


public OwnedCollection(String playerId, List<T> collection) {
    super(playerId);
    this.playerId = playerId;
    this.collection = collection;
}

}

我想从json反序列化它.我正在使用Gson库,所以
当我拨打电话时:

OwnedCollection<Skin> fromJson = new Gson().fromJson(json, new TypeToken<OwnedCollection<Skin>>() {}.getType());

一切都很好.

但是,当我尝试创建一个方法来做到这一点,我得到例外.
我尝试过以下方法:

public <T extends BaseObject> OwnedCollection<T> deserialize1(String json, Class<T> type) {
    Gson gson = new Gson();
    return gson.fromJson(json, new TypeToken<T>() {
    }.getType());
}

并调用它:

OwnedCollection<Skin> deserialize1 = deserialize1(json, Skin.class);

我得到:

java.lang.ClassCastException: org.miracledojo.karatedo.domen.item.Skin cannot be cast to org.miracledojo.karatedo.domen.item.OwnedCollection

然后:

public <T extends BaseObject> OwnedCollection<T> deserialize2(String json, Type type) {
    Gson gson = new Gson();
    return gson.fromJson(json, type);
}

并调用它:

deserialize2(json, Skin.class);

然后我得到:

java.lang.ClassCastException: org.miracledojo.karatedo.domen.item.Skin cannot be cast to org.miracledojo.karatedo.domen.item.OwnedCollection

有人有什么想法吗?
就像是:

OwnedCollection<Skin>.class

是不可能的,所以任何类似的sintax?

解决方法:

您正在为GSON解析器提供不正确的类型标记,将类型标记更改为类型为T的OwnedCollection

public <T extends BaseObject> OwnedCollection<T> deserialize1(String json, Class<T> type) {
    return new Gson().fromJson(json, new TypeToken<OwnedCollection<T>>(){}.getType());
}

标签:json,java,gson,generics,generic-programming
来源: https://codeday.me/bug/20190705/1390719.html