我有一个 JSON 字符串,看起来像 {"code": "FOO"}
.
现在我想使用 kotlinx.serialization
反序列化这个字符串.我尝试了以下方法:
import kotlinx.serialization.*
@Serializable
data class Result(val code: String?)
val decoded = Json.decodeFromString<Result>(jsonString)
当 JSON 只包含 code
时,这有效,但实际上 JSON 字符串中可以有其他键(这是我无法控制的)。我只关心code
键,但是当存在其他键时,我的应用程序崩溃。我如何只解码相关的 JSON key ?
最佳答案
在进一步调试我的应用程序后,我发现以下错误:
JsonDecodingException: Unexpected JSON token at offset 14: Encountered an unknown key 'error'. Use 'ignoreUnknownKeys = true' in 'Json {}' builder to ignore unknown keys. JSON input: {"code":"FOO","otherKey":"Something else"}
我找不到任何关于此的文档,但我设法通过将代码更改为以下内容来解决此问题:
import kotlinx.serialization.*
@Serializable
data class Result(val code: String?)
val decoded = Json { ignoreUnknownKeys = true }.decodeFromString<ErrorResponse>(jsonString)
关于json - 如何使用 kotlinx.serialization 部分解码 JSON 字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63826230/