'Retrofit/Moshi : Deserialize and keep null fields

I've seen many topics about this subject but none of them fit my needs.

I need a way to deserialize null fields into null json properties

Let's take this example:

@JsonClass(generateAdapter = true)
data class MyClass(val myField: String?)

val obj = MyClass(null)

expected behavior:

{
   "myField: null
}

By default, it just skips null fields.

I'm working with Retrofit and Moshi. I don't want to enable withNullSerialization as it will take effect to all Classes (and break the existing logic) and I want this to work for only one Class for now.

Furthermore, for performance and apk size purpose, I removed kotlin-reflect from the project. Which means I would like to avoid using reflection (KotlinJsonAdapterFactory) as many solutions point to that direction.

Is there a way to achieve this ? Thanks in advance.



Solution 1:[1]

Looking at the doc, seems you need to write a custom adapter for that specific class:

class MyClassWithNullsAdapter {
  @ToJson fun toJson(writer: JsonWriter, myClass: MyClass?,
    delegate: JsonAdapter<MyClass?>) {
    val wasSerializeNulls: Boolean = writer.getSerializeNulls()
    writer.setSerializeNulls(true)
    try {
      delegate.toJson(writer, myClass)
    } finally {
      writer.setLenient(wasSerializeNulls)
    }
  }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 romtsn