FAQ
Reviewers: golang-dev_googlegroups.com,

Message:
Hello golang-dev@googlegroups.com,

I'd like you to review this change to
https://code.google.com/p/go


Description:
encoding/json: avoid error when decoding unexported fields with json:"-"
tag

Restore the Go 1.0.3 behavior that was lost when the field cache was
introduced.

Fixes issue 4660.

Please review this at https://codereview.appspot.com/7139049/

Affected files:
M src/pkg/encoding/json/decode.go
M src/pkg/encoding/json/decode_test.go


Index: src/pkg/encoding/json/decode.go
===================================================================
--- a/src/pkg/encoding/json/decode.go
+++ b/src/pkg/encoding/json/decode.go
@@ -535,7 +535,7 @@
st := v.Type()
for i := 0; i < st.NumField(); i++ {
f := st.Field(i)
- if f.PkgPath != "" && strings.EqualFold(f.Name, key) {
+ if f.PkgPath != "" && strings.EqualFold(f.Name, key) &&
f.Tag.Get("json") != "-" {
d.saveError(&UnmarshalFieldError{key, st, f})
}
}
Index: src/pkg/encoding/json/decode_test.go
===================================================================
--- a/src/pkg/encoding/json/decode_test.go
+++ b/src/pkg/encoding/json/decode_test.go
@@ -1064,3 +1064,26 @@
}
}
}
+
+// Test handling of unexported fields that should be ignored.
+// Issue 4660
+type unexportedFields struct {
+ Name string
+ m map[string]interface{} `json:"-"`
+ m2 map[string]interface{} `json:"abcd"`
+}
+
+func TestUnmarshalUnexported(t *testing.T) {
+ input := `{"Name": "Bob", "m": {"x": 123}}`
+ out := &unexportedFields{}
+ err := Unmarshal([]byte(input), out)
+ if err != nil {
+ t.Errorf("expected no error; got: %v", err)
+ }
+
+ input = `{"Name": "Alice", "m": {"x": 123}, "m2": {"y": 456}}`
+ err = Unmarshal([]byte(input), out)
+ if ufe, ok := err.(*UnmarshalFieldError); !ok || ufe.Key != "m2" {
+ t.Errorf("expected field error on m2; got: %v", err)
+ }
+}

Search Discussions

Related Discussions

Discussion Navigation
viewthread | post
Discussion Overview
groupgolang-dev @
categoriesgo
postedJan 17, '13 at 2:11a
activeJan 17, '13 at 12:28p
posts3
users2
websitegolang.org

2 users in discussion

Rickarnoldjr: 2 posts Adg: 1 post

People

Translate

site design / logo © 2022 Grokbase