Java/Android 中使用Protocol Buffers传输数据
Protocol Buffers是一种数据交互格式,是Google公司开源的一种数据描述语言,能够将结构化数据序列化,可用于数据存储、通信协议等方面。相比于现在流行的XML以及Json格式存储数据,通过Protocol Buffers来定义的文件体积更小,解析速度更快(官方文档中明确提到),目前已经支持很多的主流语言,本篇文章主要介绍一下如何在Java/Android中使用。
下载Protocol Buffers
在官方地址或者maven仓库中下载即可。
编写Proto文件
本文采用官方文档中的例子来演示一下:官方文档例子地址
proto文件中,Message类似Java中的类,里面可以定义我们需要的属性:
message Person {
required string name = 1;
required int32 id = 2;
optional string email = 3;
enum PhoneType {
MOBILE = 0;
HOME = 1;
WORK = 2;
}
message PhoneNumber {
required string number = 1;
optional PhoneType type = 2 [default = HOME];
}
repeated PhoneNumber phone = 4;
}
通过上面的官方例子,我们可以知道Protocol Buffers是支持枚举的。
参数声明
You specify that message fields are one of the following:
required: a well-formed message must have exactly one of this field.
optional: a well-formed message can have zero or one of this field (but not more than one).
repeated: this field can be repeated any number of times (including zero) in a well-formed message. The order of the repeated values will be preserved.
required:一个message中必须有一个的字段。
optional:一个message中可选的:可以有1一个也可以有0个。
repeated:在一个message中可以重复任意次(包括0),但是会保留他们的顺序。
可以理解为Java中的集合