Reputation: 51
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?
Upvotes: 4
Views: 241
Reputation: 3367
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());
}
Upvotes: 1