赞
踩
个人网站:yedajiang44.com
Protocol Buffers是在网络通讯或者数据存储时用到的一种语言无关、平台无关、可扩展的序列化结构数据格式。类似于XML、json,不过比XML、json更小、更快、更简单。
你首先要定义自己想要的数据结构(在 .proto 文件中定义数据结构信息),经过Protocol Buffers 编译后生成.java代码文件,就可以根据.java里的数据对象来进行读写操作。
即编写Person.protol文件,类似于定义Dto。
示例
- syntax = "proto3";
- package ProtocolBuffersDemo;
-
- message Person {
- string name = 1;
- int32 id = 2; // Unique ID number for this person.
- string email = 3;
-
- enum PhoneType {
- MOBILE = 0;
- HOME = 1;
- WORK = 2;
- }
-
- message PhoneNumber {
- string number = 1;
- PhoneType type = 2;
- }
-
- repeated PhoneNumber phones = 4;
- }
-
- // Our address book file is just one of these.
- message AddressBook {
- repeated Person people = 1;
- }

运行protocol buffer 编译器去编译.proto文件,可以根据你选择的语言生成相应的代码文件。
1、首先到github下载protocolbuffers/protobuf你所需系统对应已编译好的发布版,如果你会c++也可以下载源码自己编译
2、我的是win系统,所以下载后将解压后的protoc.exe
添加到环境变量中,方便使用
3、调出Windows的命令行,输入protoc --version
出现版本号,说明编译器可以使用了。
4、执行protoc -I=$SRC_DIR --csharp_out=$DST_DIR $SRC_DIR/Person.proto
生成c#类,如果不报错说明执行成功,此时对应的输出目录会有个Person.cs文件
上面的$SRC_DIR
表示存放message.proto文件的路径,$DST_DIR
表示生成cs文件存放的路径。如果Person.proto文件与protoc.exe在同一个目录下-I=$SRC_DIR
可以省略。
- class Program
- {
- static void Main(string[] args)
- {
- var yedajing44 = new Person
- {
- Id = 1234,
- Name = "yedajiang44",
- Email = "yedajiang44@163.com",
- Phones = {
- new Person.Types.PhoneNumber { Number = "123456789", Type = Person.Types.PhoneType.Home },
- new Person.Types.PhoneNumber { Number = "987654321", Type = Person.Types.PhoneType.Work }
- }
- };
- var json = yedajing44.ToString();
- Console.WriteLine($"序列化:{json}");
- yedajing44 = Person.Parser.ParseJson(json);
- Console.WriteLine($"反序列化{yedajing44}");
- Console.ReadKey();
- }
- }

运行结果如下:
源码已开源至github:地址
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。