Is there a simple way to make specific generated Kotlin JsonAdapters to serialize nulls?
I have a class Foo with fields that have to be serialized as nulls but I also have many other classes that should not serialize nulls. All classes are annotated with @JsonClass(generateAdapter = true).
I created this factory for Foo and registered it with Moshi. It seems to override whatever registration Moshi codegen does with the generated FooJsonAdapter.
class FooFactory : JsonAdapter.Factory {
private lateinit var adapter: JsonAdapter<Foo>
override fun create(type: Type, annotations: MutableSet<out Annotation>, moshi: Moshi): JsonAdapter<*>? {
return if (type == Foo::class.java) {
if (!this::adapter.isInitialized) {
adapter = FooJsonAdapter(moshi).serializeNulls()
}
adapter
} else moshi.nextAdapter<Any>(this, type, annotations)
}
}
Is this overriding guaranteed to work? Or is there a simple way to do this?
It would be easiest if there's a class annotation like @SerializeNulls and Moshi codegen would properly register the generated FooJsonAdapter with a call to serializeNulls().
Probably something like this:
return if (type == Foo::class.java) {
moshi.nextAdapter<Any>(this, type, annotations).serializeNulls()
} else {
null
}
Most helpful comment
Probably something like this: