https://kotlinlang.org logo
Title
p

Pushpendra Parmar

04/05/2023, 1:31 AM
Hi, I am a little lost here. I want to serialize a map with a third party class as a key. I couldn't find in docs where to add custom serializer module.
Map<RealmUUID, Long>
I created this serializer but don't know how to use
@OptIn(ExperimentalSerializationApi::class)
@Serializer(forClass = RealmUUID::class)
object RealmUUIDSerializer : KSerializer<RealmUUID> {
	override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("RealmUUID", PrimitiveKind.STRING)

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

	override fun deserialize(decoder: Decoder): RealmUUID {
		val string = decoder.decodeString()
		return RealmUUID.from(string)
	}
}
e

Emil Kantis

04/05/2023, 7:26 AM
I think you can annotate the type-parameter to your map
Map<@Serializable(with = RealmUUIDSerializer::class) RealmUUID, Long>
p

Pushpendra Parmar

04/05/2023, 3:57 PM
Thank you. But it is still throwing exception
can't be used in JSON as a key in the map. It should have either primitive or enum kind
but found another way using
json.encodeToString(MapSerializer(RealmUUIDSerializer, Long.serializer()), objectMetadataList)