Fix issue147

This commit is contained in:
Masaaki Goshima 2021-03-11 18:33:31 +09:00
parent d84b6bca18
commit be35ec63b8
1 changed files with 32 additions and 0 deletions

View File

@ -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))
}
}