【问题标题】:Kotlin serialisation of field that can be String or an Array of Strings可以是字符串或字符串数​​组的字段的 Kotlin 序列化
【发布时间】:2021-11-29 12:14:27
【问题描述】:

我当前的项目使用 Kotlin 序列化来使用一系列远程 RESTFul API。

API 响应是 Json,我无法修改它们。

其中一个 API 以字符串或字符串数​​组的形式返回“Person”。

如何让 Kotlin 序列化自动使用任一值?

我正在使用这个版本的 Kotlin 序列化

api 'org.jetbrains.kotlinx:kotlinx-serialization-core:1.3.0'
api 'org.jetbrains.kotlinx:kotlinx-serialization-json:1.3.0'

【问题讨论】:

  • 除了 Alexey Romanovs 的解决方案看起来可行且不错之外,我想说 JSON 本身是有问题的 API 设计。你对它有影响吗?
  • @Michiel,我同意 Json 响应是“有缺陷的”,但我不能以任何方式修改它。

标签: kotlin json-deserialization


【解决方案1】:

an example covering a similar case in the documentation。好吧,在这种情况下,它是一个 Users 的列表,如果你想将它解析为单个 Person,它会类似于

@Serializable
data class Person(
    @Serializable(with=StringListSerializer::class)
    val strings: List<String>)

object StringListSerializer :
    JsonTransformingSerializer<List<String>>(serializer<List<String>()) {
    // If response is not an array, then it is a single object that should be wrapped into the array
    override fun transformDeserialize(element: JsonElement): JsonElement =
        if (element !is JsonArray) JsonArray(listOf(element)) else element
}

(未测试)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-29
    • 1970-01-01
    相关资源
    最近更新 更多