Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to model

After looking at Stackoverflow questions I could not find any solution that fix this problem.

I am trying to use GSON and have implemented a generic method like this:

public <T> List<T> deserializeList(String json) {
    Gson gson = new Gson();
    Type type = (new TypeToken<List<T>>() {}).getType();
    return  gson.fromJson(json, type);
}

Call to this method is done through this :

parser.<Quote>deserializeList(result)

However the result that I am getting is this:

enter image description here

And when I am trying to access an object, I get this error:

 java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to model.Quote

The JSON string is:

[
    {
      "id": 269861,
      "quote": "People living deeply have no fear of death.",
      "author": "Anais Nin",
      "genre": "life",
      "tag": null,
      "createdAt": "2016-04-16T13:13:36.928Z",
      "updatedAt": "2016-04-16T13:13:36.928Z"
    }
]
like image 978
codebased Avatar asked Jul 26 '16 00:07

codebased


3 Answers

I would think you could write the method like so to explicitly provide the Type

public <T> List<T> deserializeList(String json, Type type) {
    Gson gson = new Gson();
    return  gson.fromJson(json, type);
}

Though, passing around (new TypeToken<List<Model>>() {}).getType(); looks a little messy.

I'm not too familiar with type erasure, but I bet that's related to the problem.

like image 58
OneCricketeer Avatar answered Oct 23 '22 09:10

OneCricketeer


The above parsing method is wrong and the following code is modified:

public static <T> List<T> getObjectList(String jsonString,Class<T> cls){
    List<T> list = new ArrayList<T>();
    try {
        Gson gson = new Gson();
        JsonArray arry = new JsonParser().parse(jsonString).getAsJsonArray();
        for (JsonElement jsonElement : arry) {
            list.add(gson.fromJson(jsonElement, cls));
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return list;
}
like image 21
yan peng Avatar answered Oct 23 '22 10:10

yan peng


In Kotlin, you can define a reified extension function like:

internal inline fun <reified T> Gson.fromJson(json: String) =
    fromJson<T>(json, object : TypeToken<T>() {}.type)

And then use it like:

val resultJson = "{...}"
val quotesList: List<Quote> = gson.fromJson(resultJson)

Explanation: at runtime, all generic types are erased (the compiler can create completely correct code without keeping the generic types at runtime). But if you declare a type as reified, you gain the ability to use that type within the function at runtime.

like image 37
David Miguel Avatar answered Oct 23 '22 11:10

David Miguel