-
Notifications
You must be signed in to change notification settings - Fork 628
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
How do I specify a default serializer for polymorphic or sealed types #2594
Comments
@ForteScarlet I think you are confused about |
@pdvrieze But this I think I roughly know that |
There's no way to set up a default deserializer with annotation. To distribute your polymorphic serializable classes to clients, you have to distribute |
Okay, but if I distribute the @Serializable
abstract class Base
@Serializable
class T1 : Base()
@Serializable
class T2 : Base()
@Test
fun serialTest() {
val data = "{}"
// My distribution
val defaultModule = SerializersModule {
polymorphicDefaultDeserializer(Base::class) { T1.serializer() }
}
// Clients
val clientModule = SerializersModule {
include(defaultModule)
polymorphicDefaultDeserializer(Base::class) { T2.serializer() }
// 👆 java.lang.IllegalArgumentException: Default deserializers provider for class SerTest$Base is already registered: (kotlin.String?) -> kotlinx.serialization.DeserializationStrategy<SerTest.Base>?
}
val json = Json {
isLenient = true
serializersModule = clientModule
}
val decoded = json.decodeFromString(Base.serializer(), data)
assertIs<T2>(decoded)
} Does that mean I have to rely on some documentation warning or suggestion that clients can add |
It seems our documentation is lacking in this place. There's a special val defaultModule = SerializersModule {
polymorphicDefaultDeserializer(Base::class) { T1.serializer() }
}
val clientModule = defaultModule overwriteWith SerializersModule {
polymorphicDefaultDeserializer(Base::class) { T2.serializer() }
} does what you want. |
@sandwwraith That's great! It seems that |
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 justJSON
.And I want this default to have a lower precedence than the one in
SerializersModule
, which means it can be overridden withSerializersModule.polymorphic(...) { defaultDeserializer { ... } }
.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.The text was updated successfully, but these errors were encountered: