Using protobuf-net to serialize objects without hassle

Serialization with protobuf-net

You are looking at revision 13 of this page, which may be out of date. View the latest version.  

protobuf-net is an open source .net implementation of Google's 'protocol buffer' binary serialization format.

Consider the following classes, I have included a sub-class to make it slightly more than a non-trivial example

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
    public DateTime DateOfBirth { get; set; }
    public Address Address { get; set; }
}

public class Address
{
    public string Number { get; set; }
    public string StreetName { get; set; }
}

public class ExtendedAddress : Address
{
    public string BuildingName { get; set; }
}

With v2 of protobuf-net you can build a serializer on the fly:

var protobufModel = ProtoBuf.Meta.TypeModel.Create();
AddTypeToModel<Person>(protobufModel);
AddTypeToModel<Address>(protobufModel).AddSubType(500, typeof(ExtendedAddress));
AddTypeToModel<ExtendedAddress>(protobufModel);

private MetaType AddTypeToModel<T>(RuntimeTypeModel typeModel)
{            
    var properties = typeof(T).GetProperties().Select(p => p.Name).ToArray();
    return typeModel.Add(typeof(T), true).Add(properties);            
}
Posted by: Wallace Turner
Last revised: 03 Nov, 2011 03:05 PM History
You are looking at revision 13 of this page, which may be out of date. View the latest version.

Comments

No comments yet. Be the first!

No new comments are allowed on this post.