is there a built-in way of deserializing a JSON li...
# serialization
y
is there a built-in way of deserializing a JSON list to a Kotlin
Pair
? if not, what's the least boilerplatey way to support this?
e
there isn't, and Pair is heterogenous so that can't work in all formats. possible to write a custom serializer for Json though,
Copy code
class PairAsListSerializer<A, B>(
    private val aSerializer: KSerializer<A>,
    private val bSerializer: KSerializer<B>,
) : KSerializer<Pair<A, B>> {
    override val descriptor = SerialDescriptor(
        "PairAsList<${aSerializer.descriptor.serialName}, ${bSerializer.descriptor.serialName}>",
        serialDescriptor<JsonArray>()
    )
    override fun serialize(encoder: Encoder, value: Pair<A, B>) {
        (encoder as JsonEncoder).encodeJsonElement(
            buildJsonArray {
                add(encoder.json.encodeToJsonElement(aSerializer, value.first))
                add(encoder.json.encodeToJsonElement(bSerializer, value.second))
            }
        )
    }
    override fun deserialize(decoder: Decoder): Pair<A, B> {
        val pair = (decoder as JsonDecoder).decodeJsonElement().jsonArray
        return decoder.json.decodeFromJsonElement(aSerializer, pair[0]) to
            decoder.json.decodeFromJsonElement(bSerializer, pair[1])
    }
}
thank you color 1
a
Possibly you are interested in a tuple serializer? If so, this is the issue to +1 https://github.com/Kotlin/kotlinx.serialization/issues/1906
🫡 1