Deserialise a generic list in Gson

generics, gson, java, json, serialization

Solution

There is no way to do it without passing actual type of `T` (as `Class<T>`) to your method.

But if you pass it explicitly, you can create a `TypeToken` for `List<T>` as follows:

private <T> List<T> GetListFromFile(String filename, Class<T> elementType) {
    ...
    TypeToken<ArrayList<T>> token = new TypeToken<ArrayList<T>>() {};
    List<T> something = gson.fromJson(data, token.getType());
    ...
}

See also:

- `TypeToken`

Problem

I want to write a generic function which deserialise a generic type List with Gson here is the code: ``` private <T> List<T> GetListFromFile(String filename) { //Read textfile BufferedReader reader; String data=""; try { reader = new BufferedReader(new FileReader(filename)); data = reader.readLine(); reader.close(); } catch (FileNotFoundException ex) { } catch (IOException ex) { } if (data == null) { List<T> Spiel = new ArrayList<T>(); return Spiel; } else { //get list with Deserialise Gson gson = new Gson(); List<T> something = gson.fromJson(data, new TypeToken<List<T>>(){}.getType()); return something; } } ``` But this code is not working, i get a strange structure but not a List of my type When i'am using: ``` List<concreteType> something = gson.fromJson(data, new TypeToken<List<T>>(){}.getType()); ``` i works i get a `List<concreteType>`!! But i need a generic function, how can i fix it? Regards rubiktubik

Original source