.NET: Serialize and Deserialize Using protobuf-net Based on Google Protobuf and Convert to a String

3/31/2016 8:33:14 PM

The code below will hopefully provide a simple but complete example of how you can use the Google based protobuf-net Nuget library. This example will also convert the serialized data to a string for easy storage in a database.

https://github.com/mgravell/protobuf-net

Install-Package protobuf-net
https://github.com/mgravell/protobuf-net


//declare object that needs to be serialized
//each property that needs to be serialized must be assigned a unique integer tag
[ProtoBuf.ProtoContract]
public class MyObject
{
	[ProtoBuf.ProtoMember(1)]
	public int Id { get; set; }
	[ProtoBuf.ProtoMember(2)]
	public string FirstName { get; set; }
	[ProtoBuf.ProtoMember(3)]
	public string LastName { get; set; }
}


//create object
var myObject = new MyObject()
{
	Id = 1,
	FirstName = "John",
	LastName = "Doe"
};


//serialize and convert to string (can store this string in a database)
var myObjectString = "";
using (var stream = new System.IO.MemoryStream())
{
	ProtoBuf.Serializer.Serialize<MyObject>(stream, myObject);
	myObjectString = Convert.ToBase64String(stream.ToArray());
}


//deserialize from string
var myObject2 = new MyObject();
byte[] myObjectBytes = Convert.FromBase64String(myObjectString);
using (var stream = new System.IO.MemoryStream(myObjectBytes))
{
	myObject2 = ProtoBuf.Serializer.Deserialize<MyObject>(stream);
}