栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

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

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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::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) {
  }
};

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

这个应该是设计师的本意

---

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

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

可以作为参考。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/958067.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号