I have a tree structure that looks like: ```["a", ...
# serialization
s
I have a tree structure that looks like:
Copy code
["a", "b", "c", {
	"i": 1,
	"id": "d"
}, {
	"i": 2,
	"id": "e"
}]
How would I go about deserializing this? I would like the items of the array to to be one of two sealed class types
Entry
and
Folder
. In the example above, the a, b & c values would be assigned to an
id
property on
Entry
.
Folder
is simple enough to map. I already have a class to handle the top level array. The trouble I’m having is figuring out how to do a custom serializer for the sealed class containing Entry and Folder.
d
You'll probably have to materialise the Json first. Then check if it's a string or object, then create the appropriate class.
s
For anyone who finds this later, this is what I came up with:
Copy code
@Serializer(JournalNode::class)
companion object : KSerializer<JournalNode> {
    override val descriptor = StringDescriptor.withName("JournalNode")

    override fun deserialize(decoder: Decoder): JournalNode {
        val input = decoder as? JsonInput ?: throw SerializationException("This class can be loaded only by Json")

        return when (val obj = input.decodeJson()) {
            is JsonPrimitive -> Entry(obj.content)
            is JsonObject -> {
                Folder(obj.getPrimitive("id").content, input.json.fromJson(serializer().list, obj.getArray("i")))
            }
            else -> throw JsonDecodingException(-1,"Invalid key type in journal hierarchy.")
        }
    }

    override fun serialize(encoder: Encoder, obj: JournalNode) {
        when(obj) {
            is Entry -> encoder.encodeString(obj.id)
            is Folder -> Folder.serializer().serialize(encoder, obj)
        }
    }
}