aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorJoshua Haberman <jhaberman@gmail.com>2016-05-17 17:24:15 -0700
committerJoshua Haberman <jhaberman@gmail.com>2016-05-17 17:24:15 -0700
commit718eb75b51025a3236bc4b4af90aae1b0023620f (patch)
tree4ca93d9911d6e332e2705cf7166fcaba82b17c8d
parentc8be6ee00c3afd59aee970a8c648099d78bdd576 (diff)
parentb01b1a8ebeb83689d606546d5867009d380cdecd (diff)
downloadprotobuf-718eb75b51025a3236bc4b4af90aae1b0023620f.tar.gz
protobuf-718eb75b51025a3236bc4b4af90aae1b0023620f.tar.bz2
protobuf-718eb75b51025a3236bc4b4af90aae1b0023620f.zip
Merge pull request #1548 from anandolee/master
JSON format for Any message must print @type first
-rw-r--r--python/google/protobuf/internal/json_format_test.py16
-rw-r--r--python/google/protobuf/json_format.py7
2 files changed, 22 insertions, 1 deletions
diff --git a/python/google/protobuf/internal/json_format_test.py b/python/google/protobuf/internal/json_format_test.py
index bdc9f49a..eec1f56f 100644
--- a/python/google/protobuf/internal/json_format_test.py
+++ b/python/google/protobuf/internal/json_format_test.py
@@ -458,6 +458,22 @@ class JsonFormatTest(JsonFormatBase):
'}\n'))
parsed_message = json_format_proto3_pb2.TestAny()
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):
message = any_pb2.Any()
diff --git a/python/google/protobuf/json_format.py b/python/google/protobuf/json_format.py
index 7921556e..57aa4077 100644
--- a/python/google/protobuf/json_format.py
+++ b/python/google/protobuf/json_format.py
@@ -42,6 +42,10 @@ Simple usage example:
__author__ = 'jieluo@google.com (Jie Luo)'
+try:
+ from collections import OrderedDict
+except ImportError:
+ from ordereddict import OrderedDict #PY26
import base64
import json
import math
@@ -208,7 +212,8 @@ def _AnyMessageToJsonObject(message, including_default):
"""Converts Any message according to Proto3 JSON Specification."""
if not message.ListFields():
return {}
- js = {}
+ # Must print @type first, use OrderedDict instead of {}
+ js = OrderedDict()
type_url = message.type_url
js['@type'] = type_url
sub_message = _CreateMessageFromTypeUrl(type_url)