diff --git a/encode_test.go b/encode_test.go index cfdfa6a..10c7d8c 100644 --- a/encode_test.go +++ b/encode_test.go @@ -3,6 +3,7 @@ package json_test import ( "bytes" "encoding" + stdjson "encoding/json" "errors" "fmt" "log" @@ -1674,3 +1675,34 @@ func TestOmitEmpty(t *testing.T) { t.Errorf(" got: %s\nwant: %s\n", got, optionalsExpected) } } + +type testNullStr string + +func (v *testNullStr) MarshalJSON() ([]byte, error) { + if *v == "" { + return []byte("null"), nil + } + + return []byte(*v), nil +} + +func TestIssue147(t *testing.T) { + type T struct { + Field1 string `json:"field1"` + Field2 testNullStr `json:"field2,omitempty"` + } + got, err := json.Marshal(T{ + Field1: "a", + Field2: "b", + }) + if err != nil { + t.Fatal(err) + } + expect, _ := stdjson.Marshal(T{ + Field1: "a", + Field2: "b", + }) + if !bytes.Equal(expect, got) { + t.Fatalf("expect %q but got %q", string(expect), string(got)) + } +}