I have the following problem regarding serializati...
# serialization
p
I have the following problem regarding serialization of polymorphic enum classes:
Copy code
interface ExampleInterface

@Serializable
enum class Example: ExampleInterface {
    TEST,
    TEST2
}


@Serializable
enum class Example2: ExampleInterface {
    WOW,
    WOW2
}

@Serializable
data class ExampleWrapper(val m: ExampleInterface)

fun main() {

    val module = SerializersModule {
        polymorphic(ExampleInterface::class) {
            Example::class with Example.serializer()
            Example2::class with Example2.serializer()
        }
    }

    val json = Json(JsonConfiguration.Stable, context = module)
    val jsonData = json.stringify(ExampleWrapper.serializer(), ExampleWrapper(Example.TEST))
    println(jsonData)
}
When I run this, the following error message is displayed:
Copy code
Uncaught Kotlin exception: kotlin.IllegalStateException: Enums cannot be serialized polymorphically with 'type' parameter. You can use 'JsonConfiguration.useArrayPolymorphism' instead
Now if I do what the error message says, I will get back something like this:
Copy code
{
  "m": [
    "barcodeParser.Example",
    "TEST"
  ]
}
But I would rather have it look like this:
Copy code
{
  "m": "TEST"
}
How can I achieve this?
k
You can't get the following with you module
Copy code
json
{
	"m":"TEST"
}
Without array polymorphism you could maybe have the following if it weren't for the fact that it seems that Enum's can't be used in polymorphism
Copy code
json
{
	"m":{"type":"Example", "value":"TEST"}
}
The only way I see to fix this is to write a custom serializer.
p
I've tried to write a custom serializer, but don't really know how to fix the problem. I still get the same error message, even if I write my own. Not sure what to look for though, the documentation doesn't really tell me much.
The library also seems to have problems if the enum has anonymous classes. It tries to find the serializer for the e.g. Example.TEST class, but it can never find one and you can also never declare it.
k
This is a way I came up with
p
Thanks, this works for me!