Unfortunately, you cannot do what you are trying to do due to erasing styles in Java.
The TypeToken destruction used by various libraries that do deserialization tries to get around this, but you cannot use it with the type parameter of the type you are trying to do. Type T is removed at runtime, and Gson can no longer determine the actual type, so it returns a Map .
Edit to add:. To get around this, you need to go into the TypeToken , and not try to create it in the method. This allows you to find out the type. The hard bit in your case is you want to return List<T> , but the TypeToken is actually ListResponse<T> . Because of this, you need to understand Generics a bit and deduce the TypeToken type with a restriction:
public <V extends ListResponse<T>> List<T> getAll(JSONObject response, TypeToken<V> token) throws IOException { ... V responseObject = Shared.gson.fromJson(response.toString(), token.getType()); ... }
When you call this, you need to pass an instance of TypeToken , but then it will work.
Response<Brewer> responseHandler = new Response<Brewer>(); TypeToken<ListResponse<Brewer>> token = new TypeToken<ListResponse<Brewer>>(){}; brewerList = responseHandler.getAll(response, token);
Brian roach
source share