gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 09:08:57 27 4
gpt4 key购买 nike

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

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

这是我的代码:

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 cannot be cast to com.readbook.chinesepoetry.data.model.Response

我在网上查到了这个异常,很多人说这是因为 kotlin 泛型删除。但是,我检查了我的代码,他们确实有 reified关键字。

最佳答案

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

只需获取对象的类

关于java - 为什么 java.lang.ClassCastException : com. google.gson.internal.LinkedTreeMap 无法转换为 com.readbook.chinesepoetry.data.model.Response?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59564380/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com