2

Kotlinx文档似乎没有涵盖这一点,我想知道是否有办法为现有类编写自定义序列化程序。就我而言,我需要序列化 ​​PointF 和 Color。对于 PointF,我已经这样做了:

object MyPointFAsStringSerializer : KSerializer<MyPointF>
{
    override val descriptor: SerialDescriptor =
        buildClassSerialDescriptor("Point") {
            element<Float>("x")
            element<Float>("y")
        }

    override fun serialize(encoder: Encoder, value: MyPointF) =
        encoder.encodeStructure(descriptor) {
            encodeFloatElement(descriptor, 0, (value.x))
            encodeFloatElement(descriptor, 1, (value.y))
        }

    override fun deserialize(decoder: Decoder): MyPointF =
        decoder.decodeStructure(descriptor) {
            var x = -1f
            var y = -1f
            while (true) {
                when (val index = decodeElementIndex(descriptor)) {
                    0 -> x = decodeFloatElement(descriptor, 0)
                    1 -> y = decodeFloatElement(descriptor, 1)
                    CompositeDecoder.DECODE_DONE -> break
                    else -> error("Unexpected index: $index")
                }
            }
            MyPointF(x, y)
        }
}


@Serializable(with = MyPointFAsStringSerializer::class)
class MyPointF()
{
    var x: Float = Float.MAX_VALUE
    var y: Float = Float.MAX_VALUE

    constructor(x: Float, y: Float) : this()
    {
        this.x = x
        this.y = y
    }
    
    fun pointF () : PointF = PointF(this.x, this.y)
}

但是,这种方法迫使我在 PointF 和 MyPointF 之间来回切换。我想知道如何将相同的序列化程序附加到现有的类(即,PointF)。在 Swift 中,我只是简单地通过 using 来做到这一点encodeToString,它实际上告诉编译器在序列化时如何处理这种对象。但我似乎无法为 Kotlin 找到方法。任何建议将不胜感激。

4

1 回答 1

2

绝对可以使用 kotlinx 序列化来序列化 3rd-party 类。你可以在这里找到文档

object PointFAsStringSerializer : KSerializer<PointF> {
    override val descriptor: SerialDescriptor =
        buildClassSerialDescriptor("Point") {
            element<Float>("x")
            element<Float>("y")
        }

    override fun serialize(encoder: Encoder, value: PointF) =
        encoder.encodeStructure(descriptor) {
            encodeFloatElement(descriptor, 0, (value.x))
            encodeFloatElement(descriptor, 1, (value.y))
        }

    override fun deserialize(decoder: Decoder): PointF =
        decoder.decodeStructure(descriptor) {
            var x = -1f
            var y = -1f
            while (true) {
                when (val index = decodeElementIndex(descriptor)) {
                    0 -> x = decodeFloatElement(descriptor, 0)
                    1 -> y = decodeFloatElement(descriptor, 1)
                    CompositeDecoder.DECODE_DONE -> break
                    else -> error("Unexpected index: $index")
                }
            }
            PointF(x, y)
        }
}

fun main() {
    println(Json.encodeToString(PointFAsStringSerializer, PointF(1.1f, 2.2f)))
}
于 2021-03-06T13:06:53.717 回答