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.
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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With