Hi all! I have some issues with sealed classes and...
# ktor
j
Hi all! I have some issues with sealed classes and JSON. If I do not wrap a sealed class in a wrapper then the discriminator is not send out
With a wrapper around my class it looks like this:
Copy code
{
  "solution": {
    "type": "com.klitsie.pubquiz.common.question.solution.SolutionV0.SingleSolutionV0",
    "solution": "123",
    "id": "8db60275-45ae-4ba3-a463-8cac0cd5afce"
  }
}
If I directly try to serialize the class, it looks like this:
Copy code
{
  "solution": "123",
  "id": "514df2d1-ffc9-4691-9087-6af334721811"
}
This is my json setup:
Copy code
Json {
            ignoreUnknownKeys = true
            isLenient = true
            prettyPrint = true
        }
Does anyone know why the discriminator is missing if I try to send out a body directly without wrapping it?
c
can you try changing the field name of "type" to something else? I wonder if that's reserved in your serialization framework
j
Well the type is the default name of the discriminator. I did not add that field myself :) that should be automatically added to your object when doing polymorphic serialisation
If I persist the Json to my Database in jsonb then I can clearly see the type discriminator being added to my object (without wrapper) but when I use it in the context of ktor it is not there
r
does setting
useArrayPolymorphism = false
in your
Json { }
block helps?
j
If I turn it on (by default it is off) I get different errors (related to the json array it creates) and I also specifically set it to false, didn't help
I figured it out: I should specifically define the type of the parent in my respond call:
Copy code
// WRONG
val mySeleadClass = SealedClass.Whatever("whatever")
call.respond(mySeleadClass )

// RIGHT
val mySeleadClass = SealedClass.Whatever("whatever")
call.respond<SealedClass>(mySeleadClass)
Because if you do not infer the type of the actual parent sealed class, it will simply serialize the child class as if it would be a stand alone the child class (and it will not be treated as a sealed class at all). https://github.com/Kotlin/kotlinx.serialization/issues/1194