Error casting TypeToken to Type when deserializing with gson

casting, eclipse, generics, gson, java

Solution

Well you're calling `TypeToken.get`, which returns a `TypeToken` - not a `Type`. in the example you're showing which works, it's using `TypeToken.getType()`, which returns a `Type`.

So you could use:

return g.fromJson(data, TypeToken.get(new ArrayList<T>().getClass()).getType());

... and that would return you a `Type`, but it may not be what you actually want. In particular, due to type erasure that will return you the same type whatever `T` you specify from the call site. If you want the type to really reflect `ArrayList<T>`, you'll need to pass the class into the method, although I'm not entirely sure where to go from there. (The Java reflection API isn't terribly clear when it comes to generics, in my experience.)

As an aside, I'd expect a method called `arrayType` to have something to do with arrays, not `ArrayList`.

Problem

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?)

Original source