如何使用 kotlinx.serialization 部分解码 JSON 字符串?

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

我有一个看起来像

{"code": "FOO"}
.

的 JSON 字符串

现在我想使用

kotlinx.serialization
反序列化这个字符串。我试过以下方法:

import kotlinx.serialization.*

@Serializable
data class Result(val code: String?)

val decoded = Json.decodeFromString<Result>(jsonString)

这在 JSON 仅包含一个

code
时有效,但实际上 JSON 字符串中可以有其他键(这是我无法控制的)。我只关心
code
键,但是当出现其他键时,我的应用程序崩溃了。

如何只解码相关的 JSON 键?

json kotlin serialization kotlinx.serialization
2个回答
22
投票

进一步调试我的应用程序后,我发现以下错误:

JsonDecodingException:偏移量 14 处出现意外的 JSON 令牌:遇到未知键“错误”。 在“Json {}”构建器中使用“ignoreUnknownKeys = true”来忽略未知键。 JSON 输入:{"code":"FOO","otherKey":"Something else"}

我找不到任何关于此的文档,但我设法通过将代码更改为以下内容来解决此问题:

import kotlinx.serialization.*

@Serializable
data class Result(val code: String?)

val decoded = Json { ignoreUnknownKeys = true }.decodeFromString<ErrorResponse>(jsonString)

0
投票

我们可以使用关键字使用所需的键部分解码 JSON:ignoreUnknownKeys

fun create(): NetworkService {
        return NetworkServiceImpl(
            client = HttpClient(Android) {
                install(Logging) {
                    level = LogLevel.ALL
                }
                install(JsonFeature) {
                    serializer = KotlinxSerializer(
                        json = kotlinx.serialization.json.Json {
                            isLenient = true
                            ignoreUnknownKeys = true
                        })
                }
            }
        )
  }
© www.soinside.com 2019 - 2024. All rights reserved.