Converting Non-Serializable Classes to a Byte Array

拈花ヽ惹草 提交于 2019-12-05 08:15:55

create a byte array from an object whose class is not marked as serializable

You can use protobuf-net v2 to accomplish this. Download the zip then reference the protobuf-net assembly.

Consider this simple class definition we want to serialize:

public class Person
{
    public string Firstname { get; set; }
    public string Surname { get; set; }
    public int Age { get; set; }
}

You can then serialize this as a byte array:

var person = new Person {Firstname = "John", Surname = "Smith", Age = 30};
var model = ProtoBuf.Meta.TypeModel.Create();
//add all properties you want to serialize. 
//in this case we just loop over all the public properties of the class
//Order by name so the properties are in a predictable order
var properties = typeof (Person).GetProperties().Select(p => p.Name).OrderBy(name => name).ToArray();
model.Add(typeof(Person), true).Add(properties);

byte[] bytes;

using (var memoryStream = new MemoryStream())
{
    model.Serialize(memoryStream, person);
    bytes = memoryStream.GetBuffer();
}

The protobuf-net serializer will serialize much faster and produce a smaller byte[] array than BinaryFormatter

caveat 1 This will only (in its current form) serialize the public properties of your class, which looks ok for your usage.
caveat 2 This is considered brittle because adding a new property to Person may mean you are unable to deserialize a Person object that was serialized with the prior TypeModel.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!