mirror of
https://github.com/golang/go.git
synced 2025-12-08 06:10:04 +00:00
encoding/json: ignore unexported fields in Unmarshal
Go 1.0 behavior was to create an UnmarshalFieldError when a json value name matched an unexported field name. This error will no longer be created and the field will be skipped instead. Fixes #4660. R=adg, rsc, bradfitz CC=golang-dev https://golang.org/cl/7139049
This commit is contained in:
parent
93d92d51dd
commit
6e3f3af4e0
2 changed files with 24 additions and 10 deletions
|
|
@ -199,7 +199,7 @@ var unmarshalTests = []unmarshalTest{
|
|||
{in: `"invalid: \uD834x\uDD1E"`, ptr: new(string), out: "invalid: \uFFFDx\uFFFD"},
|
||||
{in: "null", ptr: new(interface{}), out: nil},
|
||||
{in: `{"X": [1,2,3], "Y": 4}`, ptr: new(T), out: T{Y: 4}, err: &UnmarshalTypeError{"array", reflect.TypeOf("")}},
|
||||
{in: `{"x": 1}`, ptr: new(tx), out: tx{}, err: &UnmarshalFieldError{"x", txType, txType.Field(0)}},
|
||||
{in: `{"x": 1}`, ptr: new(tx), out: tx{}},
|
||||
{in: `{"F1":1,"F2":2,"F3":3}`, ptr: new(V), out: V{F1: float64(1), F2: int32(2), F3: Number("3")}},
|
||||
{in: `{"F1":1,"F2":2,"F3":3}`, ptr: new(V), out: V{F1: Number("1"), F2: int32(2), F3: Number("3")}, useNumber: true},
|
||||
{in: `{"k1":1,"k2":"s","k3":[1,2.0,3e-3],"k4":{"kk1":"s","kk2":2}}`, ptr: new(interface{}), out: ifaceNumAsFloat64},
|
||||
|
|
@ -1064,3 +1064,25 @@ func TestUnmarshalTypeError(t *testing.T) {
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 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}, "m2": {"y": 456}, "abcd": {"z": 789}}`
|
||||
want := &unexportedFields{Name: "Bob"}
|
||||
|
||||
out := &unexportedFields{}
|
||||
err := Unmarshal([]byte(input), out)
|
||||
if err != nil {
|
||||
t.Errorf("got error %v, expected nil", err)
|
||||
}
|
||||
if !reflect.DeepEqual(out, want) {
|
||||
t.Errorf("got %q, want %q", out, want)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue