From: David Symonds Date: Tue, 1 May 2012 01:37:44 +0000 (+1000) Subject: encoding/json: don't match field name if a JSON struct tag is present. X-Git-Tag: go1.1rc2~3275 X-Git-Url: http://www.git.cypherpunks.su/?a=commitdiff_plain;h=c3c8e35af25d99f5cfab70157e26a13b93a77e7f;p=gostls13.git encoding/json: don't match field name if a JSON struct tag is present. Fixes #3566. R=rsc CC=golang-dev https://golang.org/cl/6139048 --- diff --git a/src/pkg/encoding/json/decode.go b/src/pkg/encoding/json/decode.go index 110c6fd623..701cba9bd0 100644 --- a/src/pkg/encoding/json/decode.go +++ b/src/pkg/encoding/json/decode.go @@ -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 { diff --git a/src/pkg/encoding/json/decode_test.go b/src/pkg/encoding/json/decode_test.go index d758758d97..78768c8ba1 100644 --- a/src/pkg/encoding/json/decode_test.go +++ b/src/pkg/encoding/json/decode_test.go @@ -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}},