I have a beautiful JSON, where numbers (but not only) are "nulled" in the flowing way:
[{
"bar": ""
},
{
"bar": 123
}]
I would like to parse it to the:
data class(val bar: Long?)
I found out it can be quite easily done with following transformer.
object NullableStringSerializer : JsonTransformingSerializer<Long>(serializer()) {
override fun transformDeserialize(element: JsonElement): JsonElement =
if (element is JsonPrimitive && element.isString && element.content.isEmpty())
JsonNull
else element
}
@Serializable
data class(@Serializable(with = NullableStringSerializer::class) val bar: Long?)
This works nice, however I would like to make it more generic, so I wont need to write this transformer for every possible type.
Sadly due to the "generics" works in Kotlin, adding the type parameter to the object is not possible, and after changing it to be a class, serializer<T>()
is crying about not having a refined type.
How can I make my NullableStringSerializer
generic?