We're mid-migration from Moshi to kotlinx.serializ...
# serialization
r
We're mid-migration from Moshi to kotlinx.serialization. Our shared
Json
uses
explicitNulls = false
(omit nulls, matching Moshi defaults), which fits almost every model. But a few models need the opposite, they must emit explicit `null`s on encode. The catch is that
explicitNulls = false
always drops nulls, before any per-field
@Serializable(with=…)
or
@EncodeDefault
can run. Two options we've found, both with downsides: 1. A second
Json
(
explicitNulls = true
) + marker annotation + Retrofit converter routing those models to it. Clean at the model, but adds a whole extra
Json
+ qualifier + dual-delegate routing infra. 2. A custom
KSerializer
that builds the JSON tree by hand and writes
JsonNull
. Single
Json
, transparent through Retrofit but it can't wrap the generated serializer, so it's fully hand-written field-by-field. Lots of boilerplate. Has anyone hit this and found a third option to flip
explicitNulls
per field or class? It'd be handy if kotlinx had an
@EncodeExplicitNull
annotation, similar to the existing
@EncodeDefault
.
e
consider filing a feature request upstream, similar to
@EncodeDefault
which takes precedence over
Json { encodeDefaults }
but I think you don't actually need to create a complete new serializer, e.g. https://pl.kotl.in/Pc9H0dgH5 should just be a few lines of boilerplate per affected serializable class
r
@ephemient Wow, I had no idea about
@KeepGeneratedSerializer
and
generatedSerializer()
. That's a huge help with my boilerplate problem. I tried it out and it works really well in my case. Thanks a lot for the help. I was starting to lose my mind trying to figure out a better way to do this 😄