2

I'm building an Android app which uses Gson to serialize and deserialize objects from an API. The objects are POJOs, and I have an APIProvider class which is extended by individual Providers for each type of object (e.g. ProfileProvider extends APIProvider). I've created the APIProvider generic class in order to abstract caching.

The problem I'm having is with generics in the generic class APIProvider.

If I use the following line:

List<T> objects = gson.fromJson(cachedObjects, new TypeToken<List<Profile>>(){}.getType());

then everything works correctly. As soon as I try to abstract Profile and do the following:

List<T> objects = gson.fromJson(cachedObjects, new TypeToken<List<T>>(){}.getType());

I get the following error:

java.lang.ClassCastException: com.google.gson.internal.StringMap cannot be cast to org.buffer.android.core.Profile

Any help would be awesome.

joelg
  • 83
  • 1
  • 9
  • possible duplicate of [Using generics with GSON](http://stackoverflow.com/questions/4226738/using-generics-with-gson) –  Sep 05 '12 at 06:42
  • Thanks @RC. I noticed that one and tried a similar solution, however the fact I'm using List seemed to give me some trouble. If you have any ideas of how a solution might look, it would be massively appreciated! – joelg Sep 05 '12 at 06:45
  • 1
    Same solution as explained in http://stackoverflow.com/a/4597155/180100 you'll have to pass a concrete TypeToken –  Sep 05 '12 at 06:49
  • 2
    Thanks @RC, that's working now. I passed `new TypeToken>(){}.getType()` to the method as `mType` and then used `List objects = gson.fromJson(cachedObjects, mType);`. Appreciate the speedy help. – joelg Sep 05 '12 at 06:53

0 Answers0