为什么java.lang.ClassCastException:com.google.gson.internal.LinkedTreeMap无法转换为com.readbook.chinesepoetry.data.model.Response?

问题描述 投票:0回答:1

我是Kotlin Android开发人员的初学者。我遇到了这个问题,我不知道如何解决。

为了保持Rx流调用,我定义了一个kotlin扩展函数Observable<T>.toTraditional(),但是遇到了异常。

这是我的代码:

class Test {
    @Test
    fun test() {
        val json = "{\"result\":{\"curPage\":1,\"data\":[{\"id\":1,\"name\":\"关雎\",\"dynasty\":\"先秦\",\"poet\":\"佚名\",\"content\":\"钟鼓乐之。\"},{\"id\":1213,\"name\":\"伐檀\",\"dynasty\":\"先秦\",\"poet\":\"佚名\",\"content\":\"钟鼓乐之。\"}],\"pageCount\":388,\"size\":20,\"total\":7756},\"status\":1,\"message\":\"成功\"}"
        Observable.create<Response<RecommendListBean>> {
            val response = getResponse<Response<RecommendListBean>>(json)
            it.onNext(response)
        }.toTraditional().subscribe({},{
            println(it)
        })
    }

    inline fun <reified T> getResponse(json: String): T {
        return fromJson(json)
    }

    inline fun <reified T> Observable<T>.toTraditional(): Observable<T> {
        return map {
            val toJson = Gson().toJson(it)
            // In fact, I convert simplified chinese in json to traditional chinese.
            // Here, I intentionally omit that code to make my problem more clearly.
            val result = fromJson<T>(toJson)
            result
        }
    }

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

此外,我需要提供我的三个bean:

data class Response<T>(
        val message: String,
        @SerializedName(value = "result", alternate = ["data"])
        val result: T,
        val status: Int
)
data class RecommendListBean(
        val curPage: Int,
        val data: List<PoetryBean>,
        val pageCount: Int,
        val size: Int,
        val total: Int
)
data class PoetryBean (
    val content: String,
    val dynasty: String,
    val id: Int,
    val name: String,
    val poet: String
)

在运行上述代码后,出现错误:

java.lang.ClassCastException:com.google.gson.internal.LinkedTreeMap无法转换为com.readbook.chinesepoetry.data.model.Response

我已经在互联网上查询了此异常,许多人说这是因为Kotlin泛型被删除了。但是,我检查我的代码,他们确实有reified关键字。

java android kotlin
1个回答
1
投票
fun <R :Any> Observable<R>.toTraditional(): Observable<R> {
return map {
    val toJson = Gson().toJson(it)
    // In fact, I convert simplified chinese in json to traditional chinese.
    // Here, I intentionally omit that code to make my problem more clearly.
    val result = Gson().fromJson<R>(toJson,it.javaClass)
    result
  }
}

仅获取对象的类

© www.soinside.com 2019 - 2024. All rights reserved.