https://kotlinlang.org logo
Title
b

Bao Le Duc

02/16/2023, 9:18 AM
Hi, is there a way to provide a fallback/default deserializer when
JsonClassDiscriminator
is not found? Background: I have a data class
@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

Dominaezzz

02/16/2023, 10:13 AM
Yes, you can specify it when creating the JSON serial format
b

Bao Le Duc

02/16/2023, 10:14 AM
Could you give a bit more details? I got an exception likes
kotlinx.serialization.json.internal.JsonDecodingException: Polymorphic serializer was not found for class discriminator 'some unknown type'
d

Dominaezzz

02/16/2023, 10:16 AM
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

Bao Le Duc

02/16/2023, 10:21 AM
found it
polymorphicDefaultDeserializer(MessagingPayload::class) {
                UnkownMessagingPayload.serializer()
            }
Thanks for the tips @Dominaezzz
j

Jorge Rodríguez

02/16/2023, 7:37 PM
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.