Lek*_*ath 3 generics json gson kotlin
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
)
Run Code Online (Sandbox Code Playgroud)
例外:java.lang.ClassCastException: class com.google.gson.internal.LinkedTreeMap cannot be cast to class RpcResult
在不使用函数的情况下将 json 字符串转换为数据类对象时,它按预期工作,但从辅助函数执行相同的代码不起作用,而是引发上述异常。我在这里缺少什么?
Far*_*rid 12
这是由于运行时的类型擦除。在 Kotlin 中,您可以通过使函数内联reified类型来解决此问题:
Change your function from:
fun <T> fromJson(json: String?): T {
return Gson().fromJson<T>(json, object: TypeToken<T>(){}.type)
}
Run Code Online (Sandbox Code Playgroud)
To:
inline fun <reified T> fromJson(json: String?): T {
return Gson().fromJson<T>(json, object: TypeToken<T>(){}.type)
}
Run Code Online (Sandbox Code Playgroud)
For further reading check this out: https://kotlinlang.org/docs/reference/inline-functions.html
| 归档时间: |
|
| 查看次数: |
2879 次 |
| 最近记录: |