encoding/json: always ignore embedded pointers to unexported struct types

CL 60410 fixes a bug in reflect that allows assignments to an embedded
field of a pointer to an unexported struct type.
This breaks the json package because unmarshal is now unable to assign
a newly allocated struct to such fields.

In order to be consistent in the behavior for marshal and unmarshal,
this CL changes both marshal and unmarshal to always ignore
embedded pointers to unexported structs.

Fixes #21357

Change-Id: If62ea11155555e61115ebb9cfa5305caf101bde5
Reviewed-on: https://go-review.googlesource.com/76851
Run-TryBot: Joe Tsai <thebrokentoaster@gmail.com>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Ian Lance Taylor <iant@golang.org>
This commit is contained in:
Joe Tsai 2017-11-09 20:14:47 -08:00 committed by Joe Tsai
parent 510327012b
commit 0cee4b7b78
3 changed files with 33 additions and 6 deletions

View file

@ -195,6 +195,11 @@ type embed struct {
Q int
}
type Issue21357 struct {
*embed
R int
}
type Loop struct {
Loop1 int `json:",omitempty"`
Loop2 int `json:",omitempty"`
@ -866,6 +871,20 @@ var unmarshalTests = []unmarshalTest{
err: fmt.Errorf("json: unknown field \"extra\""),
disallowUnknownFields: true,
},
// Issue 21357.
// Ignore any embedded fields that are pointers to unexported structs.
{
in: `{"Q":1,"R":2}`,
ptr: new(Issue21357),
out: Issue21357{R: 2},
},
{
in: `{"Q":1,"R":2}`,
ptr: new(Issue21357),
err: fmt.Errorf("json: unknown field \"Q\""),
disallowUnknownFields: true,
},
}
func TestMarshal(t *testing.T) {