Kotlin序列化:找不到"UUID"类型的序列化器 [英] Kotlin serialization: Serializer has not been found for type 'UUID'
问题描述
我正在使用Kotlin序列化来序列化包含UUID字段的自定义类型
I am using Kotlin Serialization to serialize a custom type which contains a UUID field
@Serializable
data class MyDataClass {
val field1: String,
val field2: UUID
}
我遇到以下错误,不知道该怎么办:
I got the following error and did not know what to do:
Serializer has not been found for type 'UUID'. To use context serializer as fallback, explicitly annotate type or property with @Contextual
推荐答案
遵循部分,我意识到我必须编写一个看起来像这样的对象才能真正帮助UUID序列化/反序列化,即使UUID
已经实现了java.io.Serializable
:
After following the Kotlin Custom Serializer section of the Kotlin Serialization Guide, I realized I had to write an object that looks like this to actually help the UUID serialize/ deserialize, even though UUID
already implements java.io.Serializable
:
object UUIDSerializer : KSerializer<UUID> {
override val descriptor = PrimitiveSerialDescriptor("UUID", PrimitiveKind.STRING)
override fun deserialize(decoder: Decoder): UUID {
return UUID.fromString(decoder.decodeString())
}
override fun serialize(encoder: Encoder, value: UUID) {
encoder.encodeString(value.toString())
}
}
// And also update the original data class:
@Serializable
data class FaceIdentifier(
val deviceId: String,
@Serializable(with = UUIDSerializer::class)
val imageUUID: UUID,
val faceIndex: Int
)
事实证明,我必须针对多种类型执行此操作:例如Rect,Uri,所以如果可能的话,我将使用Java序列化...如果您知道更简单的方法,请告诉我.
Well it turns out I have to do this for a lot of types: e.g. Rect, Uri, so I will be using Java serialization if possible... Let me know if you know a simpler way.
这篇关于Kotlin序列化:找不到"UUID"类型的序列化器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!