简体   繁体   中英

generic method passing parramaters - java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap

I have a simple generic class:

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;
}

}

I want to deserialize it from json. I am using Gson library, so When i call the line:

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

everything is working fine.

But when i try to create a method for doing this i get exceptions. I have tried the following:

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

and calling it with:

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

i get:

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

then:

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

and calling it with:

deserialize2(json, Skin.class);

then i get:

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

Does anybody have any ideas? Something like:

OwnedCollection<Skin>.class

is not possible, so any similar sintax?

You are giving the GSON parser the incorrect type token, change the type token to be an OwnedCollection of type T

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM