nemo
nemo

Reputation: 123

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.

Upvotes: 3

Views: 3368

Answers (3)

Roman Minenok
Roman Minenok

Reputation: 9368

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.

Upvotes: 2

newacct
newacct

Reputation: 122489

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?

Upvotes: 3

Guillaume Polet
Guillaume Polet

Reputation: 47607

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.

Upvotes: 0

Related Questions