可以是字符串或字符串数​​组的字段的 Kotlin 序列化

Kotlin serialisation of field that can be String or an Array of Strings

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

API的回复是Json,我无法修改。

API 中的一个 returns 作为字符串或字符串数​​组的“人”。

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

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

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

an example covering a similar case in the documentation。好吧,在那种情况下,它是一个 User 的列表,如果你想将它解析为单个 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
}

(未测试)