3

Is it possible to create a method, that parses a generic collection from jsson? My aproach above doesn't work, because at runtime gson returns an ArrayList of LinkedHasmaps here, however there is no errors at compile time.

private <T> ArrayList<T> readArray(String json)
{
    Gson gson = new Gson();
    Type collType = new TypeToken<ArrayList<T>>() {
    }.getType();
    return gson.fromJson(json, collType);
}

I have already looked at some similar questions here like: Using a generic type with Gson, but I found no solution, that really works.

Community
  • 1
  • 1
nemo
  • 123
  • 2
  • 6

3 Answers3

3

The TypeToken stuff requires you to have the type parameters fixed at compile time. Like ArrayList<String> or something. ArrayList<T> will not work.

If you can get the class object for T passed in somehow at runtime, then you can try the solution I suggested in How do I build a Java type object at runtime from a generic type definition and runtime type parameters?

Community
  • 1
  • 1
newacct
  • 119,665
  • 29
  • 163
  • 224
2

It appeared to be really simpler than most people thought:

Type collectionType = new TypeToken<ArrayList<Person>>(){}.getType();
ArrayList<Person> persons = gson.fromJson(response, collectionType);

No need to copy ParameterizedTypeImpl class as newacct suggested in his answer.

Roman Minenok
  • 9,328
  • 4
  • 26
  • 26
0

By default, in v2.1, if you don't do anything, it will be deserialized a List<Map<String,Object>>

You can register a TypeAdapterFactory for that Collection type and then determine to what kind of objects this should be actually deserialized.

Guillaume Polet
  • 47,259
  • 4
  • 83
  • 117