Hi, is it possible to override serializer? I have a library class annotated as `@Serializable` but ...
t
Hi, is it possible to override serializer? I have a library class annotated as
@Serializable
but I would like to use different serializer than default one but I can't change the library code.
e
Depends a bit on your use case. You can always specify the serializer explicitly when encoding/decoding if it's the immediate element you're trying to encode/decode. If it's nested in a structure you don't control it gets trickier.. see https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/serializers.md#serializing-3rd-party-classes
t
I can't set serializer when calling encode, I don't call it directly
e
if the library class is nested in a structure you own you could override it that way, see: https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/serializers.md#specifying-serializer-on-a-property
Are you using some framework which performs the serialization then?
t
Ktor & Kmongo, both use kotlinx.serialization
e
I'm not aware of any explicit ways to set the serializer of a specific class when constructing
Json
serializer sadly.. Could've been handy in this case? 🙂
Copy code
Json {
  useSerializerForClass<MyLibClass>(CustomLibSerializer)
}
Perhaps there's some GH issue for it
t
It would be great! Even better if it was possible to set it in serializer module
âž• 1
e
Let me know if you find or create an issue.. I'd add a thumbs up to it blob joy
e
the serialization format has influence over
@Contextual
and
@Polymorphic
serialization because the containing classes' serializers look up the members' serializers via
serializersModule
, but that's not true for other members. serializers for generics are passed as constructor parameters and all others are referenced directly, the serial format has no influence over that.