-
Notifications
You must be signed in to change notification settings - Fork 2
A Complete Example
David Taylor edited this page Oct 28, 2021
·
2 revisions
Given the following class:
class Person
{
public int Id;
public string Name;
}Here's how we can serialize it to a stream:
void SerializePerson(Person person, Stream stream)
{
var writer = new JsonObjectWriter(stream);
writer.WriteStartObject()
writer.WriteMember(1, person.Id);
writer.WriteMember(2, person.Name);
writer.WriteEndObject();
}And here's how we can read it back:
Person DeserializePerson(Stream stream)
{
var reader = new JsonObjectReader(stream);
Person person = null;
if (reader.ReadStartObject())
{
person = new Person();
while (reader.MoveToNextMember())
{
switch (reader.MemberKey)
{
case 1:
person.Id = reader.ReadValueAsInt32();
break;
case 2:
person.Name = reader.ReadValueAsString(250);
break;
}
}
reader.ReadEndObject();
}
return person;
}Note that new members can be added without breaking compatibility with older code that doesn't explicitly handle them. No extra coding required!
To serialize the object a different format, choose a different implementation of IObjectReader/Writer. No need to modify your serialization code! (See Supported Formats for details.)
This allows you to, for example, use a human-readable format like [JSON](JSON Encoding) during testing and easily switch to a more efficient binary format like [PBON](PBON Encoding) in production.