```abstract class MapNode { // Node Propertie...
# serialization
w
Copy code
abstract class MapNode {

    // Node Properties
    var isGroup by mutableStateOf(false)
    var colorIndex by mutableStateOf(0)

    // Node Children
    @Serializable(with = SnapshotStateListSerializer::class)
    var left = mutableStateListOf<MapNode>()

}
How can I write a Custom Serializer for this class ?? that serializes all these properties ! (including delegated properties)
d
You could serialize it using a wrapper class.
w
how ?
I've tried everything
d
Make the same class without delagates.
data class MapNode(val .....)
.
Then serialize that. super easy,.
w
but then I would need to convert classes and apply properties before serialization
won't I?
are you suggesting Surrogate Serializer...
d
Yeah you would need to convert but it saves you having to wr..... eEXCACTLY!!!
Surrogate!
It saves you having to write a custom serializer.
Or rather, a complex one. With a surrogate you can keep it simple.
👍 1
w
Thanks ! I'll try it and let you know if it works
Copy code
@SerialName("MapNode")
@Serializable
private class MapNodeSurrogate(
    val isGroup: Boolean,
    val colorIndex: Int,
    val left: List<MapNodeSurrogate>,
    val right: List<MapNodeSurrogate>
)

object MapNodeSerializer : KSerializer<MapNode> {

    private val serializer = MapNodeSurrogate.serializer()

    override val descriptor: SerialDescriptor = serializer.descriptor

    private fun convertToSurrogate(node: MapNode): MapNodeSurrogate {
        return MapNodeSurrogate(
            node.isGroup,
            node.colorIndex,
            node.left.map { convertToSurrogate(it) },
            node.right.map { convertToSurrogate(it) }
        )
    }

    private fun convertToNode(surrogate: MapNodeSurrogate): MapNode {
        return MapNode().apply {

        }
    }

    override fun serialize(encoder: Encoder, value: MapNode) {
        encoder.encodeSerializableValue(serializer, convertToSurrogate(value))
    }

    override fun deserialize(decoder: Decoder): MapNode {
        return convertToNode(decoder.decodeSerializableValue(serializer))
    }

}
Since map node is an abstract class , how can I make an instance , I don't know how to deal with polymorphism here
d
You should make the surrogate polymorphic too.
To save you some time, make sure all of the base class properties are abstract.
w
I still have to return instance of base class in serializer in deserialize method
d
Yes?
w
how to know which subclass I should return instance of ?
d
You can get that from the surrogate.
if (surrogate is SubClassSurrogate) { return subclass }
w
ok
Copy code
MapNodeSurrogate.serializer()
still accessing the base class serializer and using it , won't subclass properties not get serialized ?
d
It'll be fine. As long as you've registered the subclasses.
❤️ 1
👍 1
w
It works ! Thanks