Hector
Hector

Reputation: 5356

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

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'

Upvotes: 1

Views: 2871

Answers (1)

Alexey Romanov
Alexey Romanov

Reputation: 170745

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)

Upvotes: 4

Related Questions