edenman
05/26/2020, 9:24 PMFoo
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 idealedenman
05/26/2020, 9:25 PMDominaezzz
05/26/2020, 9:34 PMJsonTransformingSerializer
into your project.edenman
05/26/2020, 9:35 PMedenman
05/26/2020, 9:50 PMedenman
05/26/2020, 9:56 PMedenman
05/26/2020, 9:56 PMabstract 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)
}
}