What is the best way to deserialize a heterogenous...
# serialization
c
What is the best way to deserialize a heterogenous array that looks like this in JSON? I can write a custom serializer, but I am stuck on which descriptor to use, because
listSerialDescriptor
assumes a homogenous array.
Copy code
[{"key": "value"}, "string"]
In Swift, I can pull arbitrary types out of an
UnkeyedDecodingContainer
in any order I need
It seems like the best i can do is use polymorphic serialization for the entire array with a fixed set of subtypes and then runtime cast them, hoping that the object shapes are distinct enough to not be confused for one another because I cannot use the position in the array as a hint to the serializer even though I know the types ahead of time
a
You could also maybe serialize it into JsonElements and write something to manually walk the tree… It’s definitely not ideal, but it lets you do stuff like use the positions in the list in some more manual serialization logic https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/json.md#json-elements
c
I might have to do that because even Polymorphic does not work here – Polymorphic seems to assume JsonObject and not JsonElement
e
there is Json.useArrayPolymorphism but that isn't what you want either
you'll have to write a custom serializer, it doesn't have to be too hard if you use
ListSerializer(JsonElement.serializer())
(or equivalents) as a surrogate. It won't work for any format other than JSON, but this kind of structure also doesn't work with other formats so you're not really losing anything
c
Yep, totally. JsonElement ended up working pretty well!