0

Is there a way to distinguish between Successful and Failed responses based on the value of ok field in a response JSON?

@Serializable
sealed class Response {
    @Serializable
    data class Successful(
        @SerialName("ok")
        val ok: Boolean,

        @SerialName("payload")
        val payload: Payload
    ) : Response()

    @Serializable
    data class Failed(
        @SerialName("ok")
        val ok: Boolean,

        @SerialName("description")
        val description: String
    ) : Response()
}

So, for {"ok":true, "payload":…} I want to get Successful class, and for {"ok":false, "description":…}Failed.

I know that there is similar question — Deserializing into sealed subclass based on value of field — but it uses type field, and I don't have any type discriminators in the JSON (the meaning of ok is not type discrimination (though it can be used that way with some hacks, probably))

madhead
  • 31,729
  • 16
  • 153
  • 201
  • Have you tried creating a Custom serializer for `Response`? https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/custom_serializers.md – Bartek Lipinski Mar 24 '20 at 14:37
  • Any examples of how to write it? I think I may need something like `kotlinx.serialization.internal.AbstractPolymorphicSerializer`. The problem is that in it's case values are stored as `{"type": "Type Descriptor", "value": {...}}`, and I may need some kind of a lookahead into the value. – madhead Mar 24 '20 at 14:45

0 Answers0