'class com.google.gson.internal.LinkedTreeMap cannot be cast to class Return
java.lang.ClassCastException: class com.google.gson.internal.LinkedTreeMap cannot be cast to class
val listReturn: Return<List<Category>> = Http.getObject("category/get")//fail
fun <T> getObject(url: String): T {
val type = object : TypeToken<T>() {}.type
return Gson().fromJson(get(url), type)
}
val get = Http.get("category/get")
val type = object : TypeToken<Return<List<Category>>>() {}.type
println(Gson().fromJson<Return<List<Category>>>(get, type).data)//success
Solution 1:[1]
This is caused by type erasure on the JVM: at runtime, the function getObject doesn't know what type T is. You need to make it an inline function and use a reified type. Change it as follows and it should work:
inline fun <reified T> getObject(url: String): T {
... leave body as before
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | k314159 |
