Protocol Buffer(简称Protobuf) 是 Google 公司内部提供的数据序列化和反序列化标准,与 JSON 和 XML 格式类似,以 .proto 作为扩展名,同样大小的对象,相比 XML 和 JSON 格式, Protobuf 序列化后所占用的空间最小。
Protocol Buffers 是一种轻便高效的结构化数据存储格式,可用于通讯协议、数据存储等领域的语言无关、平台无关、可扩展的序列化结构数据格式,目前提供了 C# 语言的 API 接口可供使用。
首先通过NuGet安装protobuf-net程序包:
Install-Package protobuf-net
定义您要序列化的类型:
[ProtoContract]
class Person {
[ProtoMember(1)]
public int Id {get;set;}
[ProtoMember(2)]
public string Name {get;set;}
[ProtoMember(3)]
public Address Address {get;set;}
}
[ProtoContract]
class Address {
[ProtoMember(1)]
public string Line1 {get;set;}
[ProtoMember(2)]
public string Line2 {get;set;}
}
如上所示,需要在类型上标记 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);
}
要进一步学习 Protobuf 知识,请参阅以下博客: