Reviewers:
golang-dev_googlegroups.com,
Message:
Hello
golan...@googlegroups.com,
I'd like you to review this change to
https://go.googlecode.com/hg/
Description:
encoding/json: don't panic marshaling anonymous non-struct field
Add a check for this case and don't try to follow the anonymous
type's non-existent fields.
Fixes issue 4474.
Please review this at
https://codereview.appspot.com/6945065/
Affected files:
M src/pkg/encoding/json/encode.go
M src/pkg/encoding/json/encode_test.go
Index: src/pkg/encoding/json/encode.go
===================================================================
--- a/src/pkg/encoding/json/encode.go
+++ b/src/pkg/encoding/json/encode.go
@@ -641,6 +641,13 @@
// Must be pointer.
ft = ft.Elem()
}
+
+ // If it's not a struct, simply record the field.
+ if ft.Kind() != reflect.Struct {
+ fields = append(fields, field{name: ft.Name(), index: index, typ: ft})
+ continue
+ }
+
nextCount[ft]++
if nextCount[ft] == 1 {
next = append(next, field{name: ft.Name(), index: index, typ: ft})
Index: src/pkg/encoding/json/encode_test.go
===================================================================
--- a/src/pkg/encoding/json/encode_test.go
+++ b/src/pkg/encoding/json/encode_test.go
@@ -186,3 +186,23 @@
t.Errorf("got %q, want %q", got, want)
}
}
+
+type IntType int
+
+type MyStruct struct {
+ IntType
+}
+
+func TestAnonymousNonstruct(t *testing.T) {
+ var i IntType = 11
+ a := MyStruct{i}
+ const want = `{"IntType":11}`
+
+ b, err := Marshal(a)
+ if err != nil {
+ t.Fatalf("Marshal: %v", err)
+ }
+ if got := string(b); got != want {
+ t.Errorf("got %q, want %q", got, want)
+ }
+}