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

Time:10-11

My current project employs Kotlin serialisation to consume a family of remote RESTFul API's.

The API responses are Json and I cannot amend them.

One of the API's returns a "Person" as either a String or an Array of Strings.

How cam I get Kotlin serialisation to automatically consume either value?

Im using this version of Kotlin serialisation

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

CodePudding user response:

There is an example covering a similar case in the documentation. Well, in that case it's a list of Users, if you want to resolve it to a single Person, it would be something like

@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
}

(not tested)

  • Related