How to serialize null?

Using kotlinx.serialization…

val card: Card? = getCard(...)
val json = if (card == null) "null" 
           else Json.stringify(Card.serializer(), card)

That’s fairly clear, but I’m just wondering if I’m missing some standard way to handle T? when you have a KSerializer<T>

I guess “null” is isn’t technically JSON format, but if I have a HTTP response that sends a Card? I’d rather do it this way than create a data class CardResponse(card: Card?) just for this.

What you need is a NullableSerializer that wraps the Card serializer. Note that nullable values at top level may still not be supported by the encoder/decoder (format).

Perfect, thanks!

(post withdrawn by author, will be automatically deleted in 24 hours unless flagged)