]> Cypherpunks repositories - gostls13.git/commitdiff
encoding/json: don't match field name if a JSON struct tag is present.
authorDavid Symonds <dsymonds@golang.org>
Tue, 1 May 2012 01:37:44 +0000 (11:37 +1000)
committerDavid Symonds <dsymonds@golang.org>
Tue, 1 May 2012 01:37:44 +0000 (11:37 +1000)
Fixes #3566.

R=rsc
CC=golang-dev
https://golang.org/cl/6139048

src/pkg/encoding/json/decode.go
src/pkg/encoding/json/decode_test.go

index 110c6fd62386e5af5ad5871c9b31067c4175c569..701cba9bd048e75c187ed419c14dfc5ecb44fc75 100644 (file)
@@ -504,10 +504,15 @@ func (d *decodeState) object(v reflect.Value) {
                                }
                                // First, tag match
                                tagName, _ := parseTag(tag)
-                               if tagName == key {
-                                       f = sf
-                                       ok = true
-                                       break // no better match possible
+                               if tagName != "" {
+                                       if tagName == key {
+                                               f = sf
+                                               ok = true
+                                               break // no better match possible
+                                       }
+                                       // There was a tag, but it didn't match.
+                                       // Ignore field names.
+                                       continue
                                }
                                // Second, exact field name match
                                if sf.Name == key {
index d758758d97816352b6c50bc2451cb2cea3d6d510..78768c8ba19443cdd0a85c1bcfd485f5235ad9aa 100644 (file)
@@ -18,6 +18,10 @@ type T struct {
        Z int `json:"-"`
 }
 
+type U struct {
+       Alphabet string `json:"alpha"`
+}
+
 type tx struct {
        x int
 }
@@ -72,6 +76,10 @@ var unmarshalTests = []unmarshalTest{
        // Z has a "-" tag.
        {`{"Y": 1, "Z": 2}`, new(T), T{Y: 1}, nil},
 
+       {`{"alpha": "abc", "alphabet": "xyz"}`, new(U), U{Alphabet: "abc"}, nil},
+       {`{"alpha": "abc"}`, new(U), U{Alphabet: "abc"}, nil},
+       {`{"alphabet": "xyz"}`, new(U), U{}, nil},
+
        // syntax errors
        {`{"X": "foo", "Y"}`, nil, nil, &SyntaxError{"invalid character '}' after object key", 17}},
        {`[1, 2, 3+]`, nil, nil, &SyntaxError{"invalid character '+' after array element", 9}},