Home > Enterprise >  class com.google.gson.internal.LinkedTreeMap cannot be cast to class Return
class com.google.gson.internal.LinkedTreeMap cannot be cast to class Return

Time:03-29

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

CodePudding user response:

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
}
  • Related