Protobuf数据序列化和反序列化

Protocol Buffer(简称Protobuf) 是 Google 公司内部提供的数据序列化和反序列化标准,与 JSON 和 XML 格式类似,以 .proto 作为扩展名,同样大小的对象,相比 XML 和 JSON 格式, Protobuf 序列化后所占用的空间最小。
 
 
Protocol Buffers 是一种轻便高效的结构化数据存储格式,可用于通讯协议、数据存储等领域的语言无关、平台无关、可扩展的序列化结构数据格式,目前提供了 C# 语言的 API 接口可供使用。
首先通过NuGet安装protobuf-net程序包:Install-Package protobuf-net
定义您要序列化的类型:
 
 1 [ProtoContract]
 2 class Person {
 3 [ProtoMember(1)]
 4 public int Id {get;set;}
 5 [ProtoMember(2)]
 6 public string Name {get;set;}
 7 [ProtoMember(3)]
 8 public Address Address {get;set;}
 9 }
10 [ProtoContract]
11 class Address {
12 [ProtoMember(1)]
13 public string Line1 {get;set;}
14 [ProtoMember(2)]
15 public string Line2 {get;set;}
16 }

 

如上所示,需要在类型上标记 ProtoContract 特性,在属性上标记 ProtoMember 并指定序号。
序列化数据,将序列化结果写到 prson.bin 文件中,当然文件扩展名可以随意指定:
var person = new Person {
Id = 12345, Name = "Fred",
Address = new Address {
Line1 = "Flat 1",
Line2 = "The Meadows"
}
};
using (var file = File.Create("person.bin")) {
Serializer.Serialize(file, person);
}

 

反序列化数据,我们将刚刚序列化后的 rson.bin 文件进行反序列化:
Person newPerson;
using (var file = File.OpenRead("person.bin")) {
newPerson = Serializer.Deserialize(file);
}

  

posted @ 2021-10-26 22:34  Tammytan  阅读(468)  评论(0编辑  收藏  举报