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 找到方法。任何建议将不胜感激。