proto3 由于字段为默认值(比如0值、空串、false等),导致输出json对应字段被隐藏

message foo{

int32 val;

}

如果val值为0,则pb2json 转出来的json串中没有 val字段。

除了数值型,其他类型字段值等于默认值的均会有此问题,比如为空串的字符串、为0的枚举、为false的bool 等等。

proto2下没有此问题,proto3下有此问题。

问题根源在于,protobuf v3 设计者认为这是特性(不是bug哦),符合减少字节传递的期望。

帖子传送门:

帖子1:

Protobuf Documentation on Optional Fields And Default Values:

> For enums, the default value is the first value listed in the enum's type definition. This means care must be taken when adding a value to the beginning of an enum value list.

帖子2:

issue on golang/protobuf:

> This is working as intended. proto3 zero-values are omitted in the JSON format too. The zero-value should be a "throwaway" value: it's also what you will see if the sender of a serialized message sets the field to an invalid or unrecognized value.

所以,解决办法有如下几种:

1. 直接换回proto2 ,使用required 限定。

2. 改为proto3风格,或者不使用0值,如:

enum Type{

    definedValue = 0;

}

改为:

enum Type{

       none =0 ;
       definedValue = 1;

}

3. c++的有如下解决办法,其他语言的可以参照(推荐):

头文件:

#include <google/protobuf/util/json_util.h>

这个头文件是在安装protobuf的include目录中。

代码:

google::protobuf::util::JsonPrintOptions options;
options.always_print_primitive_fields = true;

再将options 作为message <-> pb 时的第三个参数,进行转换

对应的源码中标识如下:

struct JsonPrintOptions {
  // Whether to add spaces, line breaks and indentation to make the JSON output
  // easy to read.
  bool add_whitespace;
  // Whether to always print primitive fields. By default primitive fields with
  // default values will be omitted in JSON joutput. For example, an int32 field
  // set to 0 will be omitted. Set this flag to true will override the default
  // behavior and print primitive fields regardless of their values.
  bool always_print_primitive_fields;

  JsonPrintOptions() : add_whitespace(false),
                       always_print_primitive_fields(false) {
  }
};

注意:

如果你是在使用 Google Protocol Buffers 的 C 版本,那么这个类是不存在的,因为 C 版本的 Protocol Buffers 没有提供 JSON 输出的功能。

如果你需要在 C 程序中使用 Protocol Buffers 并输出 JSON 格式的数据,你可以考虑使用 C++ 版本的 Protocol Buffers,然后在 C 代码中调用 C++ 版本的 Protocol Buffers 的函数。

BRPC:

假如使用的是BRPC,发现值为默认值的字段被隐藏,可以在接口中使用如下方式:

  brpc::Controller *cntl = static_cast<brpc::Controller *>(controller);
  cntl->set_always_print_primitive_fields(true);

4. 与对方约定,认为此值 has_xxx() 为false时,其为默认值。

这个应该是设计师的本意

---

具体协议规定:Language Guide (proto3)  |  Protocol Buffers  |  Google Developers

stackoverfolw的类似python 问题:python - protobuf MessageToJson removes fields with value 0 - Stack Overflow

可以作为参考。

  • 11
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值