From 92e091e9bbc0da342496a0daf2703663ab272a9b Mon Sep 17 00:00:00 2001 From: Gabriel Crispino Date: Wed, 13 Dec 2023 22:08:29 -0300 Subject: [PATCH 1/2] fix: enable isNilCheck on MarshalJson ptr --- internal/encoder/compiler.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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) From 38a0a5163d783bdcb0960163317cbcc3639121a1 Mon Sep 17 00:00:00 2001 From: Gabriel Crispino Date: Wed, 13 Dec 2023 22:09:28 -0300 Subject: [PATCH 2/2] test: add tests test: draft for omitempty on pointer receiver for MarshalJSON test: move new test onto omitempty marshaling tests --- encode_test.go | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) 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 {