Hello,
can someone tell me how to use Json serialization while preserving types. I use
polymorphism and want to save and load data from an application.
Here is a small example:
import
json,
marshal,
os
type
Node* = ref object of RootObj
InputNode* = ref object of Node
OutputNode* = ref object of Node
method signal*(this: Node) {.base.} =
echo "wrong signal!"
method signal*(this: InputNode) =
echo "input signal"
method signal*(this: OutputNode) =
echo "output signal"
var nodes: seq[Node]
nodes.add(new InputNode)
nodes.add(new OutputNode)
echo "before JSON:"
nodes[0].signal()
nodes[1].signal()
# serialization and deserialization
let data = $$nodes
nodes = to[seq[Node]](data)
echo "\nafter JSON:"
nodes[0].signal()
nodes[1].signal()
Run
The output is:
before JSON:
input signal
output signal
after JSON:
wrong signal!
wrong signal!
Run
Im also happy if you can give me an alternative solution. Thanks in advance.