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()
The output is:
before JSON:
input signal
output signal
after JSON:
wrong signal!
wrong signal!
Im also happy if you can give me an alternative solution. Thanks in advance.
Thank you for your reply.
Yes, thats what i currently do. Every type has its own list. But it feels wrong with so many different types. I'am not that experienced in Nim. Is it possible to save the typedescription as property and use it to generate the specific type? This would be useful.
For example i found in std/typetraits you can use "name" to get the type as a string.
(seq[string]) == "seq[string]"
But i cant find a way to dynamically generate a object based on a string that describes a type.