Skip to content Skip to sidebar Skip to footer

Creating Lists Of Dynamic Types

So, I'm working right now on trying to figure out how to parse a large number of different JSON objects without having to hard-code functions to serialize and deserialize each of t

Solution 1:

The answer is: You can't do what you're trying to do in Java because of type erasure.

That's the reason you have to use TypeToken and pass a Type to Gson's fromJson() method; the type information for T isn't available at runtime. Generics in Java are for the most part just compile time type checking.

Ideally you'd like to be able to do this:

public <T> List<T> createList(JsonArray a, Class<T> clazz)
{
    Typet=newTypeToken<List<T>>(){}.getType();
    returnnewGson().fromJson(a, t);
}

But you can't, because T gets erased. If you try this you'll find the result completely confusing; you get a List back, but it won't actually contain your class and throw a cast exception.

Effectively, your method would have to look like this:

public <T> List<T> createList(JsonArray a, Type t)
{
    List<T> list = newGson().fromJson(a, t);
    return list;
}

Which of course would be silly since you're now calling a method you wrote instead of just calling the method in Gson.

Edit to add:

Thinking about it, there's way around this for List types. You can use arrays:

public <T> List<T> createList(JsonArray a, Class<T[]>c){T[] array = new Gson().fromJson(a,c);
    return Arrays.asList(array);
}

Because you're not trying to rely on the generic type from inside a List and instead are passing an array type for the class... it works. A bit messy, but it works:

List<MyPojo> list = createList(a, MyPojo[].class);

Post a Comment for "Creating Lists Of Dynamic Types"