0

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?

majkrzak
  • 1,332
  • 3
  • 14
  • 30
  • Do you mean _reified_ type? – k314159 Aug 18 '22 at 15:14
  • Also, I've just tried using your serializer, but it gives an exception: `Exception in thread "main" kotlinx.serialization.json.internal.JsonDecodingException: Failed to parse 'long' JSON input: null` - even though I made sure the type is nullable `Long?` – k314159 Aug 18 '22 at 15:34

1 Answers1

0

I just couldn't get NullableStringSerializer to work with empty strings at all (are you sure yours actually works?) In the end, I got it working like this:

@Serializable
data class X(val bar: JsonPrimitive) {
   fun barValue() = bar.longOrNull
}

k314159
  • 5,051
  • 10
  • 32