关闭

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

标签: ProtoBuf序列化ProtoBuf反序列化protobufprotobuf-csharp-portc#
1850人阅读 评论(1) 收藏 举报
分类:

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

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:63148次
    • 积分:1030
    • 等级:
    • 排名:千里之外
    • 原创:40篇
    • 转载:10篇
    • 译文:1篇
    • 评论:8条
    最新评论