kotlinx.serialization icon indicating copy to clipboard operation
kotlinx.serialization copied to clipboard

Don't check kind if needn't type discriminator for enum and primitive

Open SettingDust opened this issue 1 year ago • 5 comments

What is your use-case and why do you need this feature? Output the enum and primitive correctly. If we add a PrimitiveKind descriptor to a subclass of polymorphic serializer. There is error #1486 If we add a wrapper for the primitive(https://github.com/Kotlin/kotlinx.serialization/issues/1252#issuecomment-2257655863). The result will be wrapped even if the classDiscriminatorMode = ClassDiscriminatorMode.NONE like below.

{
  "data": {
    "value": "FOO"
  }
}

Related: #1252 #1486

Describe the solution you'd like https://github.com/Kotlin/kotlinx.serialization/blob/master/formats/json/commonMain/src/kotlinx/serialization/json/internal/Polymorphic.kt#L41 Avoid failing if needn't discriminator for checkKind. Add a condition in checkKind or encodePolymorphically

val kind = actual.descriptor.kind
if(needDiscriminator || (kind !is SerialKind.ENUM && kind !is PrimitiveKind)) checkKind(kind )

SettingDust avatar Jul 30 '24 09:07 SettingDust

Can you post an example code and incorrect output, please?

sandwwraith avatar Jul 30 '24 12:07 sandwwraith

The same error with https://github.com/Kotlin/kotlinx.serialization/issues/1486. This is a FR for allowing enum and primitive in polymorphic if needn't the type information. I'll append the example to body

SettingDust avatar Jul 30 '24 12:07 SettingDust

if needn't the type information.

You always need type information when deserializing polymorphic type. Are you talking about serialization-only use case?

sandwwraith avatar Jul 30 '24 13:07 sandwwraith

You always need type information when deserializing polymorphic type. Are you talking about serialization-only use case?

https://github.com/Kotlin/kotlinx.serialization/blob/master/formats/json/commonMain/src/kotlinx/serialization/json/JsonConfiguration.kt#L78-L84 said it's a use case.

SettingDust avatar Jul 30 '24 14:07 SettingDust

https://github.com/Kotlin/kotlinx.serialization/blob/master/formats/json/commonMain/src/kotlinx/serialization/json/internal/PolymorphismValidator.kt#L45 Need modify as well

SettingDust avatar Aug 02 '24 10:08 SettingDust