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
edenman
05/26/2020, 9:25 PM
anybody know if there’s a better way to do this?
d
Dominaezzz
05/26/2020, 9:34 PM
Copy
JsonTransformingSerializer
into your project.
e
edenman
05/26/2020, 9:35 PM
ha! i like it, thanks, will try
edenman
05/26/2020, 9:50 PM
unfortunately it’s got a bunch of internal/private stuff, copying that all over seems like even worse than my current solution 😕
edenman
05/26/2020, 9:56 PM
ok actually very doable, just had to diverge from how JsonTransformingSerializer works
edenman
05/26/2020, 9:56 PM
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)
}
}