使用protobuf-csharp-port进行序列化和反序列化,以AddressBook为例
有关如何获得AddressBook,如何构建ProtoBuf环境,请看protobuf 2.在Unity的C#中引用
一、序列化
1.构建一个AddressBook对象
AddressBook.Builder addressBookBuilder = AddressBook.CreateBuilder(); Person.Builder person = Person.CreateBuilder(); person.Id = 1; person.Name = "Test"; person.Email = "test@qq.com"; addressBookBuilder.AddPerson(person); AddressBook addressBook = addressBookBuilder.Build();2.调用WriteTo进行序列化
MemoryStream stream = new MemoryStream(); addressBook.WriteTo(stream); byte[] buffer = stream.ToArray();
3.提取方法,传入ProtoBuf对象(即AddressBook对象)及其泛型,得到byte数组
public static byte[] Serialize<TMessage, TBuilder>(TMessage protoBufObj) where TMessage : GeneratedMessage<TMessage, TBuilder> where TBuilder : GeneratedBuilder<TMessage, TBuilder>, new() { MemoryStream stream = new MemoryStream(); protoBufObj.WriteTo(stream); return stream.ToArray(); }调用方法
byte[] buffer = Serialize<AddressBook, AddressBook.Builder>(addressBook);
二、反序列化 1.通过Builder的MergeFrom方法进行反序列化
AddressBook.Builder builder = new AddressBook.Builder(); builder.MergeFrom(buffer); AddressBook result = builder.Build();2.提取方法,以序列化后的byte数组为参数,获得ProtoBuf对象
public static TMessage Deserialize<TMessage, TBuilder>(byte[] buffer) where TMessage : GeneratedMessage<TMessage, TBuilder> where TBuilder : GeneratedBuilder<TMessage, TBuilder>, new() { TBuilder builder = new TBuilder(); builder.MergeFrom(buffer); return builder.Build() as TMessage; }调用方法
AddressBook result = Deserialize<AddressBook, AddressBook.Builder>(buffer);