protobuf MessageToJson removes fields with value 0

ore*_*ano 4 python json enumeration protocol-buffers

I'm writing a Python script that receives protobufs, converts them to json objects, and pushes them to another service. I use json.loads(MessageToJson(protobuf)) to convert the protobuf to a python dictionary object. Later I convert it back to json with json.dumps(dictionary).

I have a proto with an optional enumerated field such as:

enum C_TYPE
{
    AB = 0;
    BC = 1;
    CD = 2;
}
Run Code Online (Sandbox Code Playgroud)

When I receive a proto with a field designated as BC everything works as I expect it. When I receive a proto with a field designated AB that field gets ignored -- it does not turn up in the python dictionary or subsequent json dump. A workaround I have found is to use json.loads(MessageToJson(protobuf, including_default_value_fields=True)) but that will create default values for all missing fields, not just the ones that have a 0 enumeration. It implies that the field with enumeration 0 is missing - but it's not!

What is the correct way to retrieve the value of the enumeration field when it is set to 0?

ore*_*ano 5

没有正确的方法,我错误地定义了protobuf。对于枚举领域,第一个值默认值。这意味着如果protobuf通过时没有设置值,则会将其设置为默认值,并且在转换为json时会被忽略(除非您希望保留所有默认值。)

因此,建议对默认值使用一次性使用的名称,以便能够正确地区分设置时间。即我应该将我的protobuf定义为:

enum C_TYPE
{
    NONE = 0;
    AB = 1;
    BC = 2;
    CD = 3;
}
Run Code Online (Sandbox Code Playgroud)

来自Protobuf文档中有关可选字段和默认值的信息

对于枚举,默认值为枚举类型定义中列出的第一个值。这意味着在将值添加到枚举值列表的开头时必须格外小心。

另外来自golang / protobuf问题

这按预期工作。proto3零值也以JSON格式省略。零值应该是“丢弃”值:这也是序列化邮件的发件人将字段设置为无效或无法识别的值时也会看到的值。