Error casting TypeToken to Type when deserializing with gson

Viewed 6920

I have a class that deserializes an ArrayList of generics with this function just as described in the first answer of this thread: Java abstract class function generic Type

public <T> ArrayList<T> arrayType(String data){
    return g.fromJson(data,   TypeToken.get(new ArrayList<T>().getClass()));
}

Eclipse asks me to cast TypeToken resulting in this (sinde the function fromJson needs a Type, not a TypeToken)

public <T> ArrayList<T> arrayType(String data){
    return g.fromJson(data,  (Type) TypeToken.get(new ArrayList<T>().getClass()));
}

As result I get this error:

java.lang.ClassCastException: com.google.gson.reflect.TypeToken cannot be cast to java.lang.reflect.Type

At the gson user manual they tell you this is the correct way of calling the function

Type collectionType = new TypeToken<Collection<Integer>>(){}.getType();
Collection<Integer> ints2 = gson.fromJson(json, collectionType);

and I can't see what am I doing wrong (if it is a valid answer, why am I getting this cast error?)

1 Answers
Related