代码之家  ›  专栏  ›  技术社区  ›  Hector

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

  •  0
  • Hector  · 技术社区  · 4 年前

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

    其中一个API将“Person”作为字符串或字符串数组返回。

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

    api 'org.jetbrains.kotlinx:kotlinx-serialization-core:1.3.0'
    api 'org.jetbrains.kotlinx:kotlinx-serialization-json:1.3.0'
    
    1 回复  |  直到 4 年前
        1
  •  1
  •   Alexey Romanov    4 年前

    an example covering a similar case in the documentation User s、 如果要将其解析为单个 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
    }
    

    (未测试)