-
Notifications
You must be signed in to change notification settings - Fork 3
Getting Started
To be able to use AqlaSerializer features you need to import its main namespace:
using AqlaSerializer;
The simplest way to get started is simply to write your data; for an example (I'll use C# for most examples):
class Person
{
public int Id { get; set; }
public string Name { get; set: }
public Address Address { get; set; }
}
class Address
{
public string Line1 { get; set; }
public string Line2 { get; set; }
}
That is a good start, but by itself is not enough. It is necessary to show that we intend this type to be serialized (i.e. that it is a data contract):
[SerializableType]
class Person
{
public int Id { get; set; }
public string Name { get; set: }
public Address Address { get; set; }
}
[SerializableType]
class Address
{
public string Line1 {get; set;}
public string Line2 {get; set;}
}
By default all public properties are considered to be serializable.
Since AqlaSerializer uses binary format, it is based heavily around the Stream class; this makes it possible to use with a wide variety of implementations simply. For an example, to write to a file:
var person = new Person {
Id = 12345, Name = "Fred",
Address = new Address {
Line1 = "Flat 1",
Line2 = "The Meadows"
}
};
using (var file = File.Create("person.bin")) {
Serializer.Serialize(file, person);
}
We also need to get our data back!
Person newPerson;
using (var file = File.OpenRead("person.bin")) {
newPerson = Serializer.Deserialize<Person>(file);
}
This reads the data back from "person.bin". Note we need to tell it the type this time (the <Person>), but otherwise the code is very similar.
AqlaSerializer automatically adds types to its "registry" at a time of the first occurence. But some features (like automatic inheritance handling) require you to add all the involved types before they are going to be used in the serialization process. If something does not work, the first thing you should do is ensuring that you have a proper initialization in your code. You can setup automatic registration for types in your current assembly:
Serializer.AddContracts(/* nonPublic: */ true);
This should be called only once. Just put it into your startup code.
If you add types for more than one assembly, ensure that you do this in the same order each time. You can specify an assembly as a first argument:
Serializer.AddContracts(Assembly.Load("MyDataAssembly"), true);
Everything that can be done with attributes can also be configured at runtime via RuntimeTypeModel. The Serializer.* methods are basically just shortcuts to RuntimeTypeModel.Default., so to manipulate the behaviour of Serializer., you must configure RuntimeTypeModel.Default.
Some examples are taken from the protobuf-net wiki