TypeToken cast error for input during gson deserialization

I have a class that deserializes ArrayList generalizations using this function, 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 use TypeToken, resulting in (the sinde function fromJson needs a type, not a Token type)

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

As a result, I get this error:

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

In the gson user manual, they tell you that this is the correct way to call a function

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

and I don’t see what I am doing wrong (if this is the correct answer, why do I get this error when throwing?)

+7
source share
1 answer

Well, you call TypeToken.get , which returns TypeToken - not a Type . in the example you show which works, it uses TypeToken.getType() , which returns Type .

So you can use:

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

... and this will return Type you, but it may not be what you really want. In particular, due to the erasure of the type, which will return to you the same type as the T that you indicate on the call site. If you want the type to truly reflect ArrayList<T> , you need to pass the class to the method, although I'm not quite sure where to go from there. (The Java reflection API is not very clear when it comes to generics, in my experience.)

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

+10
source

All Articles