diff --git a/encode_test.go b/encode_test.go index 1165f6a6..faade7ea 100644 --- a/encode_test.go +++ b/encode_test.go @@ -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"` @@ -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 { diff --git a/internal/encoder/compiler.go b/internal/encoder/compiler.go index 3ae39ba8..e2343502 100644 --- a/internal/encoder/compiler.go +++ b/internal/encoder/compiler.go @@ -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)