-
Notifications
You must be signed in to change notification settings - Fork 15
Non Intrusive Serialization
jacob-carlborg edited this page Mar 1, 2013
·
6 revisions
This example shows how to do non intrusive serialization. This is useful for customizing the serialization of third party types.
module main;
import orange.serialization._;
import orange.serialization.archives._;
int i;
class Base
{
int x;
}
class Foo
{
private int a_;
private int b_;
// hide the instance variables behind properties.
@property int a () { return a_; }
@property int a (int a) { return a_ = a; }
@property int b () { return b_; }
@property int b (int b) { return b_ = b; }
}
// This method will be called when the this class is serialized.
// "foo" will be the object currently being serialized
// "serializer" will be the serializer performing the serialization process.
// "key" will be the key used to serialize "foo".
void toData (Foo foo, Serializer serializer, Serializer.Data key)
{
// increment "i" just to show this method is called on serialization
i++;
// serialize the fields via properties
serializer.serialize(foo.a, "a");
serializer.serialize(foo.b, "b");
// serializer the base class
serializer.serializeBase(foo);
}
// This method will be called when the this class is deserialized.
void fromData (ref Foo foo, Serializer serializer, Serializer.Data key)
{
// increment "i" just to show this method is called on deserialization
i++;
// deserialize the fields via properties
foo.a = serializer.deserialize!(int)("a");
foo.b = serializer.deserialize!(int)("b");
// deserializer the base class
serializer.deserializeBase(foo);
}
void main()
{
auto archive = new XmlArchive!(char);
auto serializer = new Serializer(archive);
Serializer.registerSerializer!(Foo)(&toData);
Serializer.registerDeserializer!(Foo)(&fromData);
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);
}