After ~4 months or so doing a considerable amount ...
# serialization
p
After ~4 months or so doing a considerable amount of JSON rpc development that is heavily polymorphic (uses serialization extensively), my conclusion is that there are two essential paradigms for dealing with serializing polymorphic things: format + modules, or Json + serialization strategies. The latter has dominated my work so far but I have a hunch I might be selling format + modules short. If you use a lot of polymorphism and KXS, which approach do you use/prefer. If you've seen this question dealt with in a paper, written by Roman, no doubt, 🙂, do send me a link. Much appreciated.
For example, all of my polymorphic classes get encoded or decoded using something like `Json.encodeToString(SomeSerializer, data)`where the only "moving part" is
SomeSerializer
. With the format + modules approach, I would write:
format.encodeToString(data)
,
val format = Json { serializersModule = module }
private val module = SerializersModule {
contextua(SomeSerializer)
}
And I would note that
SomeSerializer
is more complex in format + module case.
Hmmm. I think I made a good choice in choosing Json + strategy.
Just thinking out loud here ... 🙂
v
Thanks for sharing! The original idea is that users have an application-specific instance of Json format (configured with contextual and polymorphic serializers and app-specific flags), while both json usages and custom serializers are as simple as possible. What you are doing, basically, is repeating the logic already implemented in our modules, but in your custom serializers. Doesn’t mean it’s bad tho, just can be a bit simpler, probably
p
@Vsevolod Tolstopyatov [JB] The following is typical of dozens of serializers in use in my app. It's pretty simple. Sometimes I use a
JsonTransformingPolymorphicSerializer
and these are a bit more complicated. The use case is to transform a huge pile of TypeScript interfaces (LSP) to Kotlin. fwiw, it took me a while to grok KXS and solve my problem but now I'm in the happy camper camp. 🙂
/**
* Use to avoid type discriminants and to register the implementation in the scope of the interface.
*/
object ContentColorRegistrationOptionsSerializer :
JsonContentPolymorphicSerializer<ColorRegistrationOptions>(ColorRegistrationOptions::class) {
override fun selectDeserializer(element: JsonElement) = ColorRegistrationOptionsImpl.serializer()
}
The code is open source on GitLab for anyone who wants to offer up ideas on how to make it simpler. The code is clean but there is a lot of it!.