i’ve got a class `Foo` that i want to deserialize ...
# serialization
e
i’ve got a class
Foo
that i want to deserialize to null if the server gives me
{}
for the json. started to implement a
JsonTransformingSerializer
but it has a type bound
<T: Any>
which appears to mean I can’t create a `JsonTransformingSerializer<Foo?>`…I’ve worked around it for now by adding the custom serialization logic on every object that has a Foo, but that’s far from ideal
anybody know if there’s a better way to do this?
d
Copy
JsonTransformingSerializer
into your project.
e
ha! i like it, thanks, will try
unfortunately it’s got a bunch of internal/private stuff, copying that all over seems like even worse than my current solution 😕
ok actually very doable, just had to diverge from how JsonTransformingSerializer works
Copy code
abstract class EmptyAsNullSerializer<T>(private val tSerializer: KSerializer<T>) : KSerializer<T?> {
  final override val descriptor: SerialDescriptor = SerialDescriptor(
    "Serializer<${tSerializer.descriptor.serialName}>(emptyAsNull)",
    tSerializer.descriptor.kind
  )

  final override fun serialize(encoder: Encoder, value: T?) {
    val output = encoder as JsonOutput
    if (value == null) {
      output.encodeNull()
      return
    } else {
      tSerializer.serialize(encoder, value)
    }
  }

  final override fun deserialize(decoder: Decoder): T? {
    val input = decoder as JsonInput
    val element = input.decodeJson()
    if ((element as JsonObject).keys.isEmpty()) {
      return null
    }
    return input.json.fromJson(tSerializer, element)
  }
}
👍 1