google.protobuf.json_format.MessageToJson changes

2019-07-07 17:16发布

问题:

I have some protocol buffer message object. So I want to serialize it in such way:

import json
from google.protobuf.json_format import MessageToJson

with open("file.json", 'w') as fjs:
    fjs.write(MessageToJson(message_object))

But it change the names of object fields. For example I had such object:

[{
    "id": "333333",
    "creation_timestamp": 2011,
}]

MessageToJson changed it fields to:

[{
  "id": "333333",
  "creationTimestamp": "2011",
}] 

i.e creation_timestamp is changed to creationTimestamp and 2011 is done to "2011". How to avoid it?

回答1:

I read the source code for this, and turns out that you can pass an option preserving_proto_field_name=True to MessageToJson.