擅长:python、mysql、java
<p><code>json_format</code>将省略“未设置”字段。在您的示例中,<code>TopConfig()</code>创建了一个空的<code>TopConfig</code>实例,即没有设置任何字段。因此,<code>{}</code>是该对象的正确JSON表示</p>
<p>然而,有一个<a href="https://github.com/protocolbuffers/protobuf/blob/9d175493a341885019d8fad6571ddc0cf69473a2/python/google/protobuf/json_format.py#L113" rel="nofollow noreferrer">^{<cd5>}</a>到<code>MessageToDict</code>几乎就是您想要的:</p>
<pre><code>including_default_value_fields: If True, singular primitive fields,
repeated fields, and map fields will always be serialized. If
False, only serialize non-empty fields. Singular message fields
and oneof fields are not affected by this option.
</code></pre>
<p>我之所以说“几乎”,是因为空的子消息字段仍然不存在</p>