Merge pull request #326 from goccy/feature/fix-issue324

Fix the case where the embedded field is at the end
This commit is contained in:
Masaaki Goshima 2022-01-20 23:54:17 +09:00 committed by GitHub
commit b2ca5f3250
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 33 additions and 3 deletions

View File

@ -2358,3 +2358,32 @@ func TestEmptyStringMarshaler(t *testing.T) {
assertErr(t, err)
assertEq(t, "struct", string(expected), string(got))
}
func TestIssue324(t *testing.T) {
type T struct {
FieldA *string `json:"fieldA,omitempty"`
FieldB *string `json:"fieldB,omitempty"`
FieldC *bool `json:"fieldC"`
FieldD []string `json:"fieldD,omitempty"`
}
v := &struct {
Code string `json:"code"`
*T
}{
T: &T{},
}
var sv = "Test Field"
v.Code = "Test"
v.T.FieldB = &sv
expected, err := stdjson.Marshal(v)
if err != nil {
t.Fatal(err)
}
got, err := json.Marshal(v)
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(expected, got) {
t.Fatalf("failed to encode. expected %q but got %q", expected, got)
}
}

View File

@ -436,12 +436,13 @@ func (c *StructCode) ToOpcode(ctx *compileContext) Opcodes {
}
if isEndField {
endField := fieldCodes.Last()
if len(codes) > 0 {
codes.First().End = endField
} else if field.isAnonymous {
if field.isAnonymous {
firstField.End = endField
lastField := c.lastAnonymousFieldCode(firstField)
lastField.NextField = endField
}
if len(codes) > 0 {
codes.First().End = endField
} else {
firstField.End = endField
}