Hello everyone. How can I serialize a `Map<Stri...
# serialization
r
Hello everyone. How can I serialize a
Map<String, Any>
?
s
You can serialize Any polymorphically:
Map<String, @Polymorphic Any>
. But I recommend you to choose more narrow scope of model. Probably you want
JsonElement
.
r
Ok thanks, I'll try it out and let you know if I have any problem 😁
I have the following class:
Copy code
@Serializable
data class TxMessage (
  val type: String, 
  val value: Map<String, @Polymorphic Any>
)
But when I try to serialize an instance of it I get
Copy code
Exception in thread "DefaultDispatcher-worker-1" java.lang.NoSuchMethodError: kotlinx.serialization.PolymorphicSerializer: method <init>()V not found
	at TxMessage.write$Self(TxMessage.kt)
this is the test I'm running:
Copy code
assertEquals(
    "{\"type\":\"myType\",\"value\":{\"first\":1,\"second\":\"second_value\",\"third\":3.3}}",
    Json.plain.stringify(TxMessage(
        type = "myType",
        value = mapOf(
            "first" to 1,
            "second" to "second_value",
            "third" to 3.3
        )
    ))
)
s
kotlinx.serialization.PolymorphicSerializer: method <init>()V not found
happens when you're trying to use kotlin 1.3.21 with lib 0.11.0. please upgrade to 1.3.30