Litote / kmongo

[deprecated] KMongo - a Kotlin toolkit for Mongo
https://litote.org/kmongo/
Apache License 2.0
781 stars 74 forks source link

kotlinx - UUID Serializer - String #411

Closed auretanos closed 1 year ago

auretanos commented 1 year ago

When I'm trying to encode a data class to a string with an UUID inside I get...

Serializer for class 'UUID' is not found.

Is there a way to use the internal serializer for uuid to get the object as a string and decode the string back to it? Or any other way I can still use the UuidRepresentation

zigzago commented 1 year ago

Does this unit test fill your needs ? https://github.com/Litote/kmongo/blob/master/kmongo-core-tests/src/main/kotlin/org/litote/kmongo/issues/Issue245UuidRepresentation.kt#L44

auretanos commented 1 year ago

Not really. Currently I use MongoDB as my main database to store user data. I need to retrieve the data very often and on multiple servers, so I thought I just use a cache like redis since it is much faster.

In redis you can just insert strings or byte data, so I need to be able to encode and decode the data class to/from a string.

I found this but I found no way to decode the string back to the data class object

zigzago commented 1 year ago

This is more a serialization issue then.

You can use CodecRegistry:


val registry = KMongoClient.createClient().getDatabase("test").codecRegistry
val codec = registry.getCodec(MyClass::class.java)
val myClass  = codec.decode(BsonDocument.parse(json), DecoderContext.builder().build())

HTH

auretanos commented 1 year ago

This is more a serialization issue then.

You can use CodecRegistry:

val registry = KMongoClient.createClient().getDatabase("test").codecRegistry
val codec = registry.getCodec(MyClass::class.java)
val myClass  = codec.decode(BsonDocument.parse(json), DecoderContext.builder().build())

HTH

I got it to work, thank you very much.

This is basically the code I used, just in case someone has the same problem.

val registry = KMongo.createClient().getDatabase("test").codecRegistry
val codec = registry.get(MyClass::class.java)
val myClass  = codec.decode(json.bson.asBsonReader(), DecoderContext.builder().build())