Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin serialization: Serializer has not been found for type 'UUID'

Tags:

android

kotlin

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
like image 356
Ben Butterworth Avatar asked Dec 22 '22 16:12

Ben Butterworth


1 Answers

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.

like image 80
Ben Butterworth Avatar answered Jan 17 '23 15:01

Ben Butterworth