0

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.

Toubap
  • 29
  • 7
  • 1
    You could use an annotation to do it for just one class. See: https://stackoverflow.com/questions/52254876/moshi-custom-qualifier-annotation-to-serialise-null-on-one-property-only/52265735#52265735 – Eric Cochran Feb 18 '22 at 22:16
  • This approach requires reflection with the KotlinJsonAdapterFactory which I would like to avoid – Toubap Feb 19 '22 at 17:43
  • 1
    It does not. The example uses that factory, but the SerializeNulls annotation in the answer does not require it. – Eric Cochran Feb 19 '22 at 21:45
  • It worked. Indeed kotlin-reflect is not required. Thanks ! – Toubap Mar 02 '22 at 11:07

1 Answers1

0

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)
    }
  }
}
romtsn
  • 11,704
  • 2
  • 31
  • 49