2

I'm using the kotlin driver and MongoDB is not allowing me to make my data class serializable so far.

Here's the class, before I add what I've tried:

@Serializable
data class Word(
    @SerialName("_id")
    @Contextual
    val id: ObjectId,
    val pos: String,
    val word: String,
    val hyphenation: String? = null,
    val related: List<String>? = null,
    val derived: List<String>? = null,
    val senses: List<Sense>,
    val forms: VerbConjugation?,
    val searchSet: Set<String>
)

Without the @Serializable annotation added, MongoDB does not give any errors.

When added @Serializable with @Contextual as the official website suggests, it crashes with:

kotlinx.serialization.SerializationException: Serializer for class 'ObjectId' is not found. Please ensure that class is marked as '@Serializable' and that the serialization compiler plugin is applied.

Making the id nullable does not change anything. I've been stuck here for hours. Please help!

2
  • Probably worth checking why you want to make it Serializable. IME, Java serialisation isn't used much these days; for Mongo it's much more usual to let Spring/Mongo do its thing, and/or to serialise to Json instead. Commented Aug 11, 2024 at 18:17
  • @gidds Unfortunately I'm using Ktor, which doesn't integrate in the sense Spring does. I ended up doing a separate serializable class WordResponse. Commented Aug 11, 2024 at 19:15

1 Answer 1

0

Not a solid answer just a workaround some how `ObjectIdSerializer` working fine in spring project but not in ktor

@Serializable(with = ObjectIdSerializer2::class)
val organisationId: ObjectId?,

@ExperimentalSerializationApi
object ObjectIdSerializer2 : KSerializer<ObjectId> {
    
    override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("ObjectIdSerializer2", PrimitiveKind.STRING)

    override fun serialize(encoder: Encoder, value: ObjectId) {
        if(encoder is BsonEncoder){
            encoder.encodeObjectId(value)
        }else {
            encoder.encodeString(value.toHexString())
        }
    }

    override fun deserialize(decoder: Decoder): ObjectId {
        if(decoder is BsonDecoder){
            return decoder.decodeObjectId()
        }
        return ObjectId(decoder.decodeString())
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.