I've got an API that sends an enum as a string or ...
# serialization
b
I've got an API that sends an enum as a string or an empty string in case it does not exist (which I'd like as a null); from googling around it looks like I need a custom serializer per type. Is that still correct or is there a better way to do that (e.g. something like @EmptyStringToNull)
✅ 1
e
Not 100% sure. But with internalised serialisation philosophy - all non standard things require own serialiser to be written
b
not sure if that's a great idea for a single case (that I've found yet)
e
Not sure what network stack you use, but for many of them you can have default json and for one end point have special
b
I'm using ktor; can you copy the default Json config and just change that part? I'd like to configure a Json bean
I'm a bit stumped who I should even implement the custom serializer
what I'd like to do is to fetch the default serializer for an enum and use that
do I want a delegating serializer?
e
Sorry not expert in ktor
Quickly checked and looks like whole new ktor instance is needed
Maybe ask #C0A974TJ9
b
no, talking about serialization
Copy code
object LanguageIsoSerializer : KSerializer<LanguageIso?> {
    private val delegate = serializer<LanguageIso>().nullable

    override val descriptor: SerialDescriptor
        get() = SerialDescriptor("at.fyayc.emporixapi.i18n.LanguageIso", delegate.descriptor)

    override fun serialize(
        encoder: Encoder,
        value: LanguageIso?
    ) {
        delegate.serialize(encoder, value)
    }

    override fun deserialize(decoder: Decoder): LanguageIso? {
        val string = decoder.decodeString()
        return if (string.isNotEmpty()) {
            delegate.deserialize(decoder)
        } else {
            null
        }
    }
}
like this?
the thing that stumps me a bit is that decoder.decodeString propably consumes the token
you could ofc also try catch, but that would also let invalid values coerce to null I think
I'll create a new post, thanks
🙌🏼 1