1

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'
2
  • 3
    Apart from that Alexey Romanovs solution looks feasible and nice, I'd say the JSON itself is questionable API design. Do you have influence on it? Commented Oct 10, 2021 at 11:16
  • @Michiel, I agree the Json response is "defective" however I cannot amend it in any way. Commented Oct 10, 2021 at 12:11

1 Answer 1

5

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)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.