I'm trying to make a custom serializer for the Color
class using the kmongo-coroutine-serialization
dependency.
I'm getting an exception when doing it saying:
Exception in thread "main" org.bson.BsonInvalidOperationException: readEndDocument can only be called when State is END_OF_DOCUMENT, not when State is VALUE.
Document I test it on as json
{
"_id": {
"$oid": "61fe4f745064370bd1473c41"
},
"id": 1,
"color": "#9ac0db"
}
ExampleDocument
class:
@Serializable
data class ExampleDocument(
@Serializable(with = ColorHexSerializer::class) val color: Color
)
ColorHexSerializer
object:
for testing purposes I always return blue
internal object ColorHexSerializer : KSerializer<Color> {
override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("color_hex", PrimitiveKind.STRING)
override fun serialize(encoder: Encoder, value: Color) {
val hex = String.format("#%06x", value.rgb and 0xFFFFFF)
encoder.encodeString(hex)
}
override fun deserialize(decoder: Decoder): Color {
return Color.BLUE
}
}
main function:
suspend fun main() {
registerSerializer(ColorHexSerializer)
val document =
KMongo.createClient("connectionString")
.getDatabase("database")
.getCollectionOfName<ExampleDocument>("testing")
.find(eq("id", 1))
.awaitFirst()
}
Converting the bson document to json and deserialize it then with kotlinxserialization works just fine. Can anyone help me here?
Thanks in advance