【protobuf】 3.使用protobuf-csharp-port进行序列化和反序列化

使用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);

阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xhyzdai/article/details/46789733
个人分类: protobuf C#
上一篇【protobuf】 2.在Unity中引用ProtoBuf
下一篇【Unity3D】 DoTween实现飘字的效果
想对作者说点什么? 我来说一句

protobuf-csharp-port-master

2017年09月26日 12.36MB 下载

protobuf-csharp-port

2016年06月21日 12.36MB 下载

没有更多推荐了,返回首页

关闭
关闭