0

I'm trying to de-serialize the following class hierarchy:

@Serializable
@JsonClassDiscriminator("op")
@OptIn(ExperimentalSerializationApi::class)
sealed class Event(val opcode: Int) {
    @Serializable @SerialName("0")
    class EXAMPLE1 private constructor(val data: Int): Event(0) // should have data, opcode
    @Serializable @SerialName("1")
    class EXAMPLE2 private constructor(val data: String): Event(1) // should have data, opcode
    
    @Serializable @SerialName("2") @JsonClassDiscriminator("eventName")
    // fails: Argument values for inheritable serial info annotation 'JsonClassDiscriminator' must be the same as the values in parent type 'Event'
    sealed class EXAMPLE3 private constructor(val eventName: String): Event(2) { // should have AT LEAST opcode, eventName
        @Serializable @SerialName("0")
        sealed class DEEPEXAMPLE1 private constructor(val data: Int): EXAMPLE3("first") // should have opcode, eventName, data (Int)
        @Serializable @SerialName("1")
        sealed class DEEPEXAMPLE2 private constructor(val data: String): EXAMPLE3("second") // should have opcode, eventName, data (String)
    }
}

The first two succeed:

  • {"op":0, "data": 5} -> Event(op:0,data:5)
  • {"op":1, "data": "hello"} -> Event(op:1,data:"hello")

However, the second two, do not, and instead gives the error upon compilation: Argument values for inheritable serial info annotation 'JsonClassDiscriminator' must be the same as the values in parent type 'Event'

  • {"op":2, "eventName": "event1", "data": 3940} -> Event(op:0,eventName:"event1",data:3940)
  • {"op":2, "eventName": "event2", "data": "hello"} -> Event(op:0,eventName:"event2",data:"hello")

Is there anyway to produce the desired results, other than JsonClassDiscriminator?

  • I suspect the plugin-generated serializer isn't clever enough to figure out how to discriminate between nested polymorphic types. Instead you could create a custom [`JsonContentPolymorphicSerializer`](https://github.com/Kotlin/kotlinx.serialization/blob/v1.4.1/docs/json.md#content-based-polymorphic-deserialization). – aSemy Dec 13 '22 at 15:28

0 Answers0