1

I'm using Kotlin (v.1.5.31) Serialization to customically serialize UUID type. But got following error: Serializer has not been found for type 'UUID'. To use context serializer as fallback, explicitly annotate type or property with @Contextual

Is it possible to use @file:UseSerializers(UUIDAsStringSerializer::class) avoiding marking @Serializable(with=UUIDAsStringSerializer::class) for each property with UUID type?

@file:UseSerializers(UUIDAsStringSerializer::class)
package mypack

// .. list of imports...

@Serializable
abstract class BusinessProcessBase {
  var id: UUID = UUID.randomUUID()
}
package mypack
@OptIn(ExperimentalSerializationApi::class)
@Serializer(forClass = UUID::class)
object UUIDAsStringSerializer: KSerializer<UUID> {
    override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("UUIDAsStringSerializer", PrimitiveKind.STRING)

    override fun serialize(encoder: Encoder, value: UUID) {
        val string = value.toString()
        encoder.encodeString(string)
    }

    override fun deserialize(decoder: Decoder): UUID {
        val string = decoder.decodeString()
        return UUID.fromString(string)
    }
}

Regarding Kotlin docs gradle.build has following options to enable OptIn's which are required for file Serializers:

tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).all {
    kotlinOptions {
        freeCompilerArgs += "-Xopt-in=kotlin.RequiresOptIn"
    }
}

Comparing to this answer I'm not sure what is wrong in my code?

Thomas Anderson
  • 511
  • 1
  • 5
  • 14
  • Does this answer your question? [Kotlin serialization: Serializer has not been found for type 'UUID'](https://stackoverflow.com/questions/65398284/kotlin-serialization-serializer-has-not-been-found-for-type-uuid) – Sean Jan 28 '22 at 17:09

0 Answers0