20

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
Ben Butterworth
  • 22,056
  • 10
  • 114
  • 167

1 Answers1

44

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.

Ben Butterworth
  • 22,056
  • 10
  • 114
  • 167
  • 1
    Kotlin serialization can't use Java serialization; despite the same name they have very different approach and requirements. – Alexey Romanov Dec 22 '20 at 00:53
  • Well it turns out most of my types are not Java Serializable, just Android `Parcelable`. People have warned against saving this to disk, so I have written the KSerializer implementations for Rect and Uri too. Now I'm fully kotlin. Nice thing is I can read the JSON output file to validate it! – Ben Butterworth Dec 22 '20 at 12:48
  • Works like charm – shervinox Feb 26 '21 at 20:53
  • Great. But is there really no library that provides such serializer implementations? – Hermann.Gruber Jul 06 '23 at 13:56