Commit 396cd361 authored by Brad Fitzpatrick's avatar Brad Fitzpatrick

json: fix decode bug with struct tag names with ,opts being ignored

When the encoder was updated to respect the ",omitempty"
struct tag options, the decoder half was never updated to know
about the new struct tag format. (the format is now an optional
name, followed by zero or more ",option" strings)

This only affected people who used ",omitempty" along with
a field name. In that case, the serialized JSON wouldn't
decode to the original value.

R=golang-dev, dvyukov
CC=golang-dev
https://golang.org/cl/4965049
parent 822804c6
...@@ -486,7 +486,7 @@ func (d *decodeState) object(v reflect.Value) { ...@@ -486,7 +486,7 @@ func (d *decodeState) object(v reflect.Value) {
if isValidTag(key) { if isValidTag(key) {
for i := 0; i < sv.NumField(); i++ { for i := 0; i < sv.NumField(); i++ {
f = st.Field(i) f = st.Field(i)
if f.Tag.Get("json") == key { if tagName(f.Tag.Get("json")) == key {
ok = true ok = true
break break
} }
...@@ -918,3 +918,13 @@ func unquoteBytes(s []byte) (t []byte, ok bool) { ...@@ -918,3 +918,13 @@ func unquoteBytes(s []byte) (t []byte, ok bool) {
} }
return b[0:w], true return b[0:w], true
} }
// tagName extracts the field name part out of the "json" struct tag
// value. The json struct tag format is an optional name, followed by
// zero or more ",option" values.
func tagName(v string) string {
if idx := strings.Index(v, ","); idx != -1 {
return v[:idx]
}
return v
}
...@@ -262,7 +262,8 @@ type All struct { ...@@ -262,7 +262,8 @@ type All struct {
Float32 float32 Float32 float32
Float64 float64 Float64 float64
Foo string `json:"bar"` Foo string `json:"bar"`
Foo2 string `json:"bar2,dummyopt"`
PBool *bool PBool *bool
PInt *int PInt *int
...@@ -331,6 +332,7 @@ var allValue = All{ ...@@ -331,6 +332,7 @@ var allValue = All{
Float32: 14.1, Float32: 14.1,
Float64: 15.1, Float64: 15.1,
Foo: "foo", Foo: "foo",
Foo2: "foo2",
String: "16", String: "16",
Map: map[string]Small{ Map: map[string]Small{
"17": {Tag: "tag17"}, "17": {Tag: "tag17"},
...@@ -391,6 +393,7 @@ var allValueIndent = `{ ...@@ -391,6 +393,7 @@ var allValueIndent = `{
"Float32": 14.1, "Float32": 14.1,
"Float64": 15.1, "Float64": 15.1,
"bar": "foo", "bar": "foo",
"bar2": "foo2",
"PBool": null, "PBool": null,
"PInt": null, "PInt": null,
"PInt8": null, "PInt8": null,
...@@ -481,6 +484,7 @@ var pallValueIndent = `{ ...@@ -481,6 +484,7 @@ var pallValueIndent = `{
"Float32": 0, "Float32": 0,
"Float64": 0, "Float64": 0,
"bar": "", "bar": "",
"bar2": "",
"PBool": true, "PBool": true,
"PInt": 2, "PInt": 2,
"PInt8": 3, "PInt8": 3,
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment