-
Notifications
You must be signed in to change notification settings - Fork 15
Custom Serialization
jacob-carlborg edited this page Feb 19, 2013
·
1 revision
This example shows how to do custom serialization of types the developer has control over.
module main;
import orange.serialization._;
import orange.serialization.archives._;
int i;
class Foo
{
int a;
int b;
// This method will be called when the this class is serialized.
// "serializer" will be the serializer performing the serialization process.
// "key" will be the key used to serialize this object.
void toData (Serializer serializer, Serializer.Data key)
{
// increment "i" just to show this method is called on serialization
i++;
// serialize the "a" field with the key "x"
serializer.serialize(a, "x");
}
void fromData (Serializer serializer, Serializer.Data key)
{
// increment "i" just to show this method is called on deserialization
i++;
// deserialize the field serialized with the key "x"
// and set the "a" field to its value
a = serializer.deserialize!(int)("x");
}
}
void main()
{
auto archive = new XmlArchive!(char);
auto serializer = new Serializer(archive);
auto foo = new Foo;
foo.a = 3;
foo.b = 4;
i = 3;
serializer.serialize(foo);
assert(i == 4);
auto f = serializer.deserialize!(Foo)(archive.untypedData);
assert(i == 5);
assert(foo.a == f.a);
}