Browse Source

fix indentation in jsonpb with Any messages

* fix indentation when Any contains message that implements JSONPBMarshaler
* add test
Joshua Humphries 6 years ago
parent
commit
e91709a02e
2 changed files with 30 additions and 1 deletions
  1. 6 1
      jsonpb/jsonpb.go
  2. 24 0
      jsonpb/jsonpb_test.go

+ 6 - 1
jsonpb/jsonpb.go

@@ -182,7 +182,12 @@ func (m *Marshaler) marshalObject(out *errWriter, v proto.Message, indent, typeU
 				return fmt.Errorf("failed to marshal type URL %q to JSON: %v", typeURL, err)
 			}
 			js["@type"] = (*json.RawMessage)(&turl)
-			if b, err = json.Marshal(js); err != nil {
+			if m.Indent != "" {
+				b, err = json.MarshalIndent(js, indent, m.Indent)
+			} else {
+				b, err = json.Marshal(js)
+			}
+			if err != nil {
 				return err
 			}
 		}

+ 24 - 0
jsonpb/jsonpb_test.go

@@ -598,8 +598,32 @@ func TestMarshalAnyJSONPBMarshaler(t *testing.T) {
 	if str != expected {
 		t.Errorf("marshalling JSON produced incorrect output: got %s, wanted %s", str, expected)
 	}
+
+	// Do it again, but this time with indentation:
+
+	marshaler := Marshaler{Indent: "  "}
+	str, err = marshaler.MarshalToString(a)
+	if err != nil {
+		t.Errorf("an unexpected error occurred when marshalling Any to JSON: %v", err)
+	}
+	// same as expected above, but pretty-printed w/ indentation
+	expected =
+`{
+  "@type": "type.googleapis.com/` + dynamicMessageName + `",
+  "baz": [
+    0,
+    1,
+    2,
+    3
+  ],
+  "foo": "bar"
+}`
+	if str != expected {
+		t.Errorf("marshalling JSON produced incorrect output: got %s, wanted %s", str, expected)
+	}
 }
 
+
 func TestMarshalWithCustomValidation(t *testing.T) {
 	msg := dynamicMessage{RawJson: `{ "foo": "bar", "baz": [0, 1, 2, 3] }`, Dummy: &dynamicMessage{}}