I want to include a serializable type `Foo` in my ...
# serialization
s
I want to include a serializable type
Foo
in my serializable API model, but I need to serialize it as an empty string if it is null. How can I do this?
Copy code
@Serializable
data class Foo(val bar: Int)
@Serializable
data class ApiModel(val foo: Foo?)
//ApiModel(null) -> {"foo":""}
//ApiModel(Foo(1)) -> {"foo":{"bar":1}}
e
Create a
JsonTransformingSerializer<Foo>
which transforms JsonNull to empty string:
Copy code
object FooOrEmptyStringSerializer : JsonTransformingSerializer<Foo>(Foo.serializer()) {
   override fun transformSerialize(element: JsonElement): JsonElement =
      when (element) {
         JsonNull -> JsonPrimitive("")
         else -> element
      }
}
s
But JsonTransformingSerializer takes
T:Any
/ not null. I am getting a null pointer exception: parameter specified as non-null is null
e
What if you change the generic type to
Foo?
Not allowed?
s
Correct.