Java Type Generic as Argument for GSON

Rodrigo Asensio picture Rodrigo Asensio · Jan 3, 2013 · Viewed 41.3k times · Source

In GSON to get a list of objects you do

Gson gson = new Gson();
Type token = new TypeToken<List<MyType>>(){}.getType();
return gson.fromJson(json, token);

It works great, but I want to go further and have MyType parametrized so I can have a common function to parse list of objects with this code

// the common function 
public <T> List<T> fromJSonList(String json, Class<T> type) {
  Gson gson = new Gson();
  Type collectionType = new TypeToken<List<T>>(){}.getType();
  return gson.fromJson(json, collectionType);
}

// the call
List<MyType> myTypes = parser.fromJSonList(jsonString, MyType.class);

Sadly returns an array of StringMaps, not the type. T is being interpreted as another generic type, not my type. Any workaround ?

Answer

oldergod picture oldergod · Jun 1, 2017

Since gson 2.8.0, you can use TypeToken#getParametized((Type rawType, Type... typeArguments)) to create the typeToken, then getType() should do the trick.

For example:

TypeToken.getParameterized(List.class, myType).getType();