Skip to content

Commit e91709a

Browse files
jhumpcybrcodr
authored andcommitted
fix indentation in jsonpb with Any messages
* fix indentation when Any contains message that implements JSONPBMarshaler * add test
1 parent d3c38a4 commit e91709a

File tree

2 files changed

+30
-1
lines changed

2 files changed

+30
-1
lines changed

jsonpb/jsonpb.go

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -182,7 +182,12 @@ func (m *Marshaler) marshalObject(out *errWriter, v proto.Message, indent, typeU
182182
return fmt.Errorf("failed to marshal type URL %q to JSON: %v", typeURL, err)
183183
}
184184
js["@type"] = (*json.RawMessage)(&turl)
185-
if b, err = json.Marshal(js); err != nil {
185+
if m.Indent != "" {
186+
b, err = json.MarshalIndent(js, indent, m.Indent)
187+
} else {
188+
b, err = json.Marshal(js)
189+
}
190+
if err != nil {
186191
return err
187192
}
188193
}

jsonpb/jsonpb_test.go

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -598,8 +598,32 @@ func TestMarshalAnyJSONPBMarshaler(t *testing.T) {
598598
if str != expected {
599599
t.Errorf("marshalling JSON produced incorrect output: got %s, wanted %s", str, expected)
600600
}
601+
602+
// Do it again, but this time with indentation:
603+
604+
marshaler := Marshaler{Indent: " "}
605+
str, err = marshaler.MarshalToString(a)
606+
if err != nil {
607+
t.Errorf("an unexpected error occurred when marshalling Any to JSON: %v", err)
608+
}
609+
// same as expected above, but pretty-printed w/ indentation
610+
expected =
611+
`{
612+
"@type": "type.googleapis.com/` + dynamicMessageName + `",
613+
"baz": [
614+
0,
615+
1,
616+
2,
617+
3
618+
],
619+
"foo": "bar"
620+
}`
621+
if str != expected {
622+
t.Errorf("marshalling JSON produced incorrect output: got %s, wanted %s", str, expected)
623+
}
601624
}
602625

626+
603627
func TestMarshalWithCustomValidation(t *testing.T) {
604628
msg := dynamicMessage{RawJson: `{ "foo": "bar", "baz": [0, 1, 2, 3] }`, Dummy: &dynamicMessage{}}
605629

0 commit comments

Comments
 (0)