Merge pull request #323 from IncSW/fix-omitempty-string-marshaler

Fix IsNilForMarshaler for string type with omitempty
This commit is contained in:
Masaaki Goshima 2022-01-20 19:56:08 +09:00 committed by GitHub
commit 8923f69dd5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 21 additions and 0 deletions

View File

@ -2339,3 +2339,22 @@ func TestIssue318(t *testing.T) {
t.Fatalf("failed to encode. expected %s but got %s", expected, string(b)) t.Fatalf("failed to encode. expected %s but got %s", expected, string(b))
} }
} }
type emptyStringMarshaler struct {
Value stringMarshaler `json:"value,omitempty"`
}
type stringMarshaler string
func (s stringMarshaler) MarshalJSON() ([]byte, error) {
return []byte(`"` + s + `"`), nil
}
func TestEmptyStringMarshaler(t *testing.T) {
value := emptyStringMarshaler{}
expected, err := stdjson.Marshal(value)
assertErr(t, err)
got, err := json.Marshal(value)
assertErr(t, err)
assertEq(t, "struct", string(expected), string(got))
}

View File

@ -589,6 +589,8 @@ func IsNilForMarshaler(v interface{}) bool {
return rv.IsNil() return rv.IsNil()
case reflect.Slice: case reflect.Slice:
return rv.IsNil() || rv.Len() == 0 return rv.IsNil() || rv.Len() == 0
case reflect.String:
return rv.Len() == 0
} }
return false return false
} }