Skip to content

How do I specify a default serializer for polymorphic or sealed types #2594

Closed
@ForteScarlet

Description

@ForteScarlet

What is your use-case and why do you need this feature?

hello. Suppose I have an abstract type 'Command' that can be extended by third parties.
I want it to have a default deserialization type target that doesn't require SerializersModule to work.
It can be deserialized by any SerialFormat, not just JSON.

And I want this default to have a lower precedence than the one in SerializersModule, which means it can be overridden with SerializersModule.polymorphic(...) { defaultDeserializer { ... } }.

@Serializable
// I want something where can specify the default serialization type.
// @PolymorphicDefault(DefaultCommand::class)
sealed class Command

@Serializable
@SerialName("c1")
data class Command1(val name: String) : Command()

@Serializable
@SerialName("c2")
data class Command2(val size: Long) : Command()

// Extensible to third parties
@Serializable
abstract class CustomCommand : Command() {
    abstract val code: Int
}

@Serializable
// Maybe here?
// @PolymorphicDefault(Command::class)
data object DefaultCommand : Command()

fun decodeCommand(format: StringFormat, raw: String): Command =
    format.decodeFromString(Command.serializer(), raw)

Describe the solution you'd like

I want to be able to specify a default serializer for a polymorphic type without additional conditions (such as having to configure SerializersModule).

Maybe provide some annotations to specify a default serialisable type at compile time? Like @PolymorphicDefault in the code used as an example above.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions