Parramaters common traversal method is 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 the Gson library, so When I call the line:
OwnedCollection<Skin> fromJson = new Gson().fromJson(json, new TypeToken<OwnedCollection<Skin>>() {}.getType());
everything works fine.
But when I try to create a method for this, I get exceptions. I've 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:
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:
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 anyone have any ideas? Something like:
OwnedCollection<Skin>.class
impossible, so any similar syntax?
+3
source to share
1 answer
You are passing the wrong type token to the GSON parser, change the type token to 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());
}
+1
source to share