JSON format for Any message must print @type first, use OrderedDict instead of {}

This commit is contained in:
Jie Luo 2016-05-17 13:01:27 -07:00
parent e4ca694cdf
commit b01b1a8ebe
2 changed files with 22 additions and 1 deletions

View File

@ -458,6 +458,22 @@ class JsonFormatTest(JsonFormatBase):
'}\n')) '}\n'))
parsed_message = json_format_proto3_pb2.TestAny() parsed_message = json_format_proto3_pb2.TestAny()
self.CheckParseBack(message, parsed_message) self.CheckParseBack(message, parsed_message)
# Must print @type first
test_message = json_format_proto3_pb2.TestMessage(
bool_value=True,
int32_value=20,
int64_value=-20,
uint32_value=20,
uint64_value=20,
double_value=3.14,
string_value='foo')
message.Clear()
message.value.Pack(test_message)
self.assertEqual(
json_format.MessageToJson(message, False)[0:68],
'{\n'
' "value": {\n'
' "@type": "type.googleapis.com/proto3.TestMessage"')
def testWellKnownInAnyMessage(self): def testWellKnownInAnyMessage(self):
message = any_pb2.Any() message = any_pb2.Any()

View File

@ -42,6 +42,10 @@ Simple usage example:
__author__ = 'jieluo@google.com (Jie Luo)' __author__ = 'jieluo@google.com (Jie Luo)'
try:
from collections import OrderedDict
except ImportError:
from ordereddict import OrderedDict #PY26
import base64 import base64
import json import json
import math import math
@ -208,7 +212,8 @@ def _AnyMessageToJsonObject(message, including_default):
"""Converts Any message according to Proto3 JSON Specification.""" """Converts Any message according to Proto3 JSON Specification."""
if not message.ListFields(): if not message.ListFields():
return {} return {}
js = {} # Must print @type first, use OrderedDict instead of {}
js = OrderedDict()
type_url = message.type_url type_url = message.type_url
js['@type'] = type_url js['@type'] = type_url
sub_message = _CreateMessageFromTypeUrl(type_url) sub_message = _CreateMessageFromTypeUrl(type_url)