Moshi: Moshi codegen and serialize nulls for one class

Created on 1 Nov 2018  路  1Comment  路  Source: square/moshi

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().

Most helpful comment

Probably something like this:

        return if (type == Foo::class.java) {
            moshi.nextAdapter<Any>(this, type, annotations).serializeNulls()
        } else {
            null
        }

>All comments

Probably something like this:

        return if (type == Foo::class.java) {
            moshi.nextAdapter<Any>(this, type, annotations).serializeNulls()
        } else {
            null
        }
Was this page helpful?
0 / 5 - 0 ratings