Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix ignoring omitempty tag when field of custom type with pointer receiver on MarshalJSON implementation (fixes #488) #489

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions encode_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,18 @@ import (
"github.com/goccy/go-json"
)

type stringAlias string

func (d *stringAlias) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf("\"%s\"", *d)), nil
}

type intAlias int

func (d *intAlias) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf("%d", *d)), nil
}

type recursiveT struct {
A *recursiveT `json:"a,omitempty"`
B *recursiveU `json:"b,omitempty"`
Expand Down Expand Up @@ -383,6 +395,18 @@ func Test_Marshal(t *testing.T) {
assertErr(t, err)
assertEq(t, "array", `{"b":{"c":1}}`, string(bytes))
})

t.Run("custom type with MarshalJSON implementation with pointer receiver", func(t *testing.T) {
type withOmit struct {
A string `json:"a,omitempty"`
B stringAlias `json:"b,omitempty"`
C intAlias `json:"c,omitempty"`
}
w := withOmit{}
bytes, err := json.Marshal(&w)
assertErr(t, err)
assertEq(t, "custom type with MarshalJSON implementation with pointer receiver", `{}`, string(bytes))
})
})
t.Run("head_omitempty", func(t *testing.T) {
type T struct {
Expand Down
2 changes: 1 addition & 1 deletion internal/encoder/compiler.go
Original file line number Diff line number Diff line change
Expand Up @@ -668,7 +668,7 @@ func (c *Compiler) structFieldCode(structCode *StructCode, tag *runtime.StructTa
}
fieldCode.value = code
fieldCode.isAddrForMarshaler = true
fieldCode.isNilCheck = false
fieldCode.isNilCheck = true
case isPtr && c.isPtrMarshalTextType(fieldType):
// *struct{ field T }
// func (*T) MarshalText() ([]byte, error)
Expand Down