Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gson: parse generic collections

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.

like image 821
nemo Avatar asked May 19 '26 21:05

nemo


2 Answers

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?

like image 114
newacct Avatar answered May 21 '26 12:05

newacct


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.

like image 40
Roman Minenok Avatar answered May 21 '26 10:05

Roman Minenok



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!