Skip to content

Commit

Permalink
fix indentation in jsonpb with Any messages
Browse files Browse the repository at this point in the history
* fix indentation when Any contains message that implements JSONPBMarshaler
* add test
  • Loading branch information
jhump authored and cybrcodr committed Apr 9, 2019
1 parent d3c38a4 commit e91709a
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
7 changes: 6 additions & 1 deletion jsonpb/jsonpb.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
}
Expand Down
24 changes: 24 additions & 0 deletions jsonpb/jsonpb_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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{}}

Expand Down

0 comments on commit e91709a

Please sign in to comment.