Hi, is there a way to provide a fallback/default d...
# serialization
b
Hi, is there a way to provide a fallback/default deserializer when
JsonClassDiscriminator
is not found? Background: I have a data class
Copy code
@Serializable
@JsonClassDiscriminator("type")
sealed interface Messaging {
    @Serializable
    @SerialName("inc_messaging_usermsg")
    data class UserMsg(
        val content: String
    ) : Messaging

    @Serializable
    @SerialName("inc_messaging_youfollow")
    data class YouFollow(
        val name: String
    ) : Messaging

    @Serializable
    @SerialName("inc_messaging_usermsgwdata")
    data class UsermsgWithData(
        val attachment: MessagingAttachment
    ) : Messaging
    
    /**
     * object Default : Messaging
     */
}
As we may add new type of messages in the future, I would add
object Default : Messaging
as a fallback option if new type is introduced
d
Yes, you can specify it when creating the JSON serial format
b
Could you give a bit more details? I got an exception likes
Copy code
kotlinx.serialization.json.internal.JsonDecodingException: Polymorphic serializer was not found for class discriminator 'some unknown type'
d
Ah no I misread the problem
You can specify a default serialiser in the serialiser module
I'm on my phone so I can't write you an example
b
found it
Copy code
polymorphicDefaultDeserializer(MessagingPayload::class) {
                UnkownMessagingPayload.serializer()
            }
Thanks for the tips @Dominaezzz
j
I think that is more accurate if you use abstract classes instead of sealed classes. What you need to be worry is that your json contains the
type
discriminator.
120 Views