Sam
03/05/2020, 9:10 PM["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.Dominaezzz
03/05/2020, 10:17 PMSam
03/06/2020, 4:37 PM@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)
}
}
}