Protobuf3 使用笔记

一、和protobuf2比,更新的内容:

1.字段前取消了required和optional两个关键字,目前可用的只有repeated关键字。
2.不可以现设置默认值了。
  a.string默认为空串
  b.枚举默认为第一个枚举定义的第一个值。并且必须是0,且为无效值,所有有意义的值请不要定义成0值
  c.bytes默认为空bytes
  d.bool默认为false
  e.数字类型默认为0
注意点:当你设置了message的变量等于 默认值时,序列化后是不占用空间的举例如下
message LogoutResponse{
uint32 result_code = 1; //数字类型 默认值为0
}
例如

LogoutResponse pt = LogoutResponse.newBuilder()
                .setResultCode(0)  //设置了默认值0
                .build();

Log.d(“test”,"pt serializedSize = "+pt.getSerializedSize() ) //serializedSize=0
此时调用 pt.getSerializedSize() 返回的值是0,也就是序列化后buf大小为0,
那么解析 序列化后buf为0的message,就可以直接使用默认值

void received(byte [] buf){
	CodedInputStream codedInputStream=null;
	LogoutResponse pt = LogoutResponse.getDefaultInstance(); //使用默认值;
    if (buf.length > 0) {
        codedInputStream = CodedInputStream.newInstance(buf);
        pt = LogoutResponse.parseFrom(codedInputStream);
     }
	Log.d("test","logout result="+pt.getResultCode() )   //result=0
}

二、protobuf3在ubuntu16.04下安装

官方地址:https://github.com/google/protobuf/blob/master/src/README.md

安装命令行如下:

$ sudo apt-get install autoconf automake libtool curl make g++ unzip
$ git clone https://github.com/google/protobuf.git
$ cd protobuf
$ git submodule update --init --recursive
$ ./autogen.sh
$ ./configure
$ make
$ make check
$ sudo make install
$ sudo ldconfig # refresh shared library cache.
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值