com.google.gson.internal.LinkedTreeMap cannot be cast to my class [duplicate]

In my opinion, due to type erasure, the parser can’t fetch the real type T at runtime. One workaround would be to provide the class type as parameter to the method.

Something like this works, there are certainly other possible workarounds but I find this one very clear and concise.

public static <T> List<T> stringToArray(String s, Class<T[]> clazz) {
    T[] arr = new Gson().fromJson(s, clazz);
    return Arrays.asList(arr); //or return Arrays.asList(new Gson().fromJson(s, clazz)); for a one-liner
}

And call it like:

String name = stringToArray(message, Product[].class).get(0).getName();

Leave a Comment