Enaium
Enaium

Reputation: 23

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

Upvotes: 1

Views: 4192

Answers (1)

k314159
k314159

Reputation: 11172

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
}

Upvotes: 2

Related Questions