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
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
)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With