json - com.google.gson.internal.LinkedTreeMap 类不能转换为 Partner 类

标签 json generics kotlin gson

import com.google.gson.Gson
import com.google.gson.reflect.TypeToken

fun main() {

    val jsonString: String = """{
        "jsonrpc": "2.0",
        "id": null,
        "result": [
            {
                "id": 1,
                "name": "Lekhnath Rijal"
            },
            {
                "id": 2,
                "name": "Administrator"
            }
        ]
    }"""

    val body1 = Gson().fromJson<RpcResult<List<Partner>>>(jsonString, object: TypeToken<RpcResult<List<Partner>>>(){}.type)

    println(body1.result[0].name) // prints Lekhnath Rijal // - As expected

    val body2 = fromJson<RpcResult<List<Partner>>>(jsonString)
    println(body2.result[0].name) // throws Exception as stated below after this code snippet
}

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

data class RpcResult<T>(
    val jsonrpc: String,
    val id: Int?,
    val result: T
)

data class Partner(
    val id: Int,
    val name: String
)

异常(exception) :java.lang.ClassCastException: class com.google.gson.internal.LinkedTreeMap cannot be cast to class RpcResult
在不使用函数的情况下将 json 字符串转换为数据类对象时,它按预期工作,但从辅助函数执行相同的代码不起作用,而是引发上述异常。我在这里错过了什么?

最佳答案

这是由于运行时的类型删除。在 Kotlin 中,您可以通过将函数与 reified 内联来解决这个问题。类型:

从以下位置更改您的功能:

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

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

如需进一步阅读,请查看:https://kotlinlang.org/docs/reference/inline-functions.html

关于json - com.google.gson.internal.LinkedTreeMap 类不能转换为 Partner 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57818332/

相关文章:

java - 为什么嵌套的通配符捕获是不可能的?

null - Kotlin 如果不为空

javascript - 使用 AJAX/JSON 进行 PHP 验证

javascript - 如何从 Rails @variable 访问 JSON?

jquery - 如何替换字符串的这一部分 - [

json - 在 HTTP POST 请求中将 JSON 发送到 Slack

generics - 引用具有关联类型的实例实现协议(protocol)

java - 如何将泛型传递到此方法中

kotlin - Kotlin泛型类型推断失败

Kotlin 构建时不会进行 Android API 版本检查