Skip to content
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

Fails to handle case where enum is the key of a map inside a data class #361

Open
andrew-smartnews opened this issue Mar 15, 2023 · 0 comments

Comments

@andrew-smartnews
Copy link

andrew-smartnews commented Mar 15, 2023

Running the following code:

package com.example

import com.beust.klaxon.Klaxon

enum class AnEnum {
    VALUE_ONE,
    VALUE_TWO,
}

typealias AMap = Map<AnEnum, Int>

data class AMapContainer(val aMap: AMap)

fun main() {
    val klaxon = Klaxon()

    val aMap = mapOf(AnEnum.VALUE_ONE to 1, AnEnum.VALUE_TWO to 2)

    val aMapContainer = AMapContainer(aMap)
    println("object:\n$aMapContainer")

    println("this works:")
    println(aMapContainer.aMap.keys.first().toString())

    val jsonString = klaxon.toJsonString(aMapContainer)
    println("json string:\n$jsonString")

    val recovered = klaxon.parse<AMapContainer>(jsonString)!!
    println("recovered object:\n$recovered")

    println("this does not work, but should:")
    println(recovered.aMap.keys.first().toString())
}

Results in the following output:

object:
AMapContainer(aMap={VALUE_ONE=1, VALUE_TWO=2})
this works:
VALUE_ONE
json string:
{"aMap" : {"VALUE_ONE": 1, "VALUE_TWO": 2}}
recovered object:
AMapContainer(aMap={VALUE_ONE=1, VALUE_TWO=2})
this does not work, but should:
Exception in thread "main" java.lang.ClassCastException: class java.lang.String cannot be cast to class com.example.AnEnum (java.lang.String is in module java.base of loader 'bootstrap'; com.example.AnEnum is in unnamed module of loader 'app')
	at com.example.KlaxonBugDemonstrationKt.main(klaxonBugDemonstration.kt:32)
	at com.example.KlaxonBugDemonstrationKt.main(klaxonBugDemonstration.kt)

Process finished with exit code 1

I would expect the code to finish printing without error. The issue is that enums are not being deserialized back into the map keys correctly, they are coming in as strings, but the compiler thinks they are enum instances.

I am using version 5.6 btw.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant