Protobuf无法序列化默认值。

9

我将使用Protobuf进行Python翻译。

我一直在尝试使用默认值,但每次运行SerializeToString()时都没有输出结果。

例如,这是我的.proto文件对象。

message Test{

    optional string lol = 1 [default="HI"];
    optional int32 num = 2 [default=200];
}

我运行

test = packets_pb2.Test()
print(test.num)
print(test.SerializeToString())

执行print(test.num)可得到200,但执行SerializeToString()没有结果(为空)。

我希望我的默认值被序列化。

您有什么好的方法吗?

先行致谢。

2个回答

12

对于使用 Protobuf 3 的任何人,可以使用 MessageToDictMessageToJsonincluding_default_value_fields 参数序列化默认值:

from google.protobuf.json_format import MessageToJson

serialized_message_with_defaults = MessageToJson(
    protobuf_instance,
    including_default_value_fields=True,  # this does it
)

有没有办法在proto2上完成它? - Paiusco

8
这是预期的工作方式。默认值不会被发送到网络上,而是接收端假定如果字段不存在,则应使用默认值。这样可以通过不发送常见值来节省网络空间。这意味着客户端和服务器必须就默认值达成一致;通常情况下,不应更改.proto文件中的默认值。
请记住,默认值的主要目的是能够处理早于该字段存在的旧客户端发送的消息。因此,这些客户端显然无法在网络上传送默认值,因为他们对其一无所知。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接