我试图将 Kotlin 的序列化包之一与以下自定义示例类一起使用。List
我将通过添加一个真实类(也需要序列化)来扩展这个类以匹配真实用例,但现在问题只是在于反序列化。我已经设法使序列化工作(在第二个代码片段中有要序列化的对象和结果String
),并且似乎反序列化过程需要以相同的方式完成(即,通过使用实例of NullableSerializer
) (事实上,我现在还没有找到一种简单而正确的方法来反序列化编码的对象。这是类,简单但想要复杂。
@Serializable(with = EhEH.Companion::class)
data class EhEH(
val i: Int
, val txt: String
//, val list: Array<String> // next feature, also with complex data, not only "simple" Strings
) {
@Serializer(forClass = EhEH::class)
companion object : KSerializer<EhEH> {
public var deserialEhEH: DeserializationStrategy<EhEH> = EhEH
override val descriptor: SerialDescriptor =
SerialDescriptor("EhEHSerializer", PrimitiveKind.STRING)
override fun serialize(encoder: Encoder, obj: EhEH) =
encoder.encodeString(obj::class.qualifiedName!!)
override fun deserialize(decoder: Decoder): EhEH {
val dec = decoder.beginStructure(descriptor)
var txt: String? = null
var x: Int? = null
var i = -1
var notFinished = true
do {
i = dec.decodeElementIndex(descriptor)
when (i) {
CompositeDecoder.READ_DONE -> notFinished = false
0 -> x = dec.decodeStringElement(descriptor, i).toIntOrNull()
1 -> txt = dec.decodeStringElement(descriptor, i)
else -> throw SerializationException("Unknown index $i")
}
} while (notFinished)
dec.endStructure(descriptor)
return EhEH(
x ?: throw MissingFieldException("x"),
txt ?: throw MissingFieldException("txt")
)
}
}
override fun toString(): String {
return "EhEH(i=$i, s='$txt')"
}
}
手动测试功能(其值被简单打印)是:
@InternalSerializationApi
fun testCborString(): String {
var e: EhEH = EhEH(
7,
"poreccio"
//, listOf("just", "another", "vacuum", "test")
)
return Cbor.dumps(
NullableSerializer(
EhEH.Companion
), e
) + " <-> " + (
{
(Cbor.load(
NullableSerializer(
EhEH.Companion
),
Cbor.dump(
NullableSerializer(EhEH.Companion), e
)
//the dumped value should be "781d62632e7472797669756d2e6170692e726573706f6e7365732e45684548"
)
as EhEH).toString()
} as () -> String)()
}
当我尝试运行它时,异常在于Cbor.load
调用并且是:
kotlinx.serialization.cbor.CborDecodingException: Expected start of map, but found 78
我是整个互联网中唯一一个有这个问题的人吗?