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:
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"
}
]
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.
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;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With