How can I serialize/deserialize a `Map<String, ...
# serialization
d
How can I serialize/deserialize a
Map<String, Map<String, Any>>
where
Any
can be one of
String
,
Set<String>
or
Map<String, String>
? I don't mind if instead of
Any
I'd have a
sealed interface AnyValue
with wrappers for those options... although I'd maybe prefer a
value class
that could have my own helper functions to cast and retreive one of those... I would know in advance which one it is using the
String
key in the inner map...
a
it might be easier to decode to a JsonObject and then ‘manually’ decode
d
Thanks! I guess I could get the Ktor client to return a String and then just use decodeToJsonElement...
a
if you wanted to set up
sealed interface AnyValue
then you could use value classes for the
String
,
Set<String>
,
Map<String, String>
- then you would have your own type hierarchy. If the value classes were
@Serializable
then the plugin-generated serializers would work just fine. The slightly tricky bit would be writing the KSerializer for
AnyValue
. It wouldn’t be too hard if you used the
JsonPolymorphicSerializer
(or whatever the real name is) provided by KxS.
d
Yeah, the only thing is that I don't think you can use value classes in sealed interfaces yet, and they would probably be boxed anyways as soon as you use the interface in the map value...
a
I’m sure you can
Something like this should work, except there’s a bug…
Copy code
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index -1 out of bounds for length 0
	at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64)
	at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70)
	at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:248)
I’ve made an issue: https://github.com/Kotlin/kotlinx.serialization/issues/2159
a
ahh right, yes. Inline classes can’t extend abstract/open/sealed classes. Inline classes can extend from interfaces though.
d
I think the problem is that as soon as you use an interface, it boxes the value class and there is no real benefit... I guess the proposed KEEP is to have a special sealed value interface that doesn't box?
Actually, it's a sealed value class in the KEEP
a
I’m confused by KT-27576… I thought that sealed classes were already implemented in 1.4. My guess is that it’s specifically regarding JVM. Currently Kotlin has a bespoke implementation that requires some under-the-hood workarounds, so if JVM supports value classes natively then Kotlin will migrate to that.
anyway, I’m promoting the use of value classes here not because they’re more performant, but because it means KxS can automatically generate a serializer that matches the ‘internal’ type, which is very convenient.
143 Views