diff --git a/codec.go b/codec.go index 321014e..206e823 100644 --- a/codec.go +++ b/codec.go @@ -1,6 +1,7 @@ package udecimal import ( + "bytes" "database/sql" "database/sql/driver" "encoding" @@ -236,6 +237,9 @@ func (d Decimal) MarshalJSON() ([]byte, error) { return []byte(`"` + d.stringBigInt(true) + `"`), nil } +// nullValue represents the JSON null value. +var nullValue = []byte("null") + // UnmarshalJSON implements the [json.Unmarshaler] interface. func (d *Decimal) UnmarshalJSON(data []byte) error { // Remove quotes if they exist. @@ -243,6 +247,11 @@ func (d *Decimal) UnmarshalJSON(data []byte) error { data = data[1 : len(data)-1] } + // null value. + if bytes.Equal(data, nullValue) { + return nil + } + return d.UnmarshalText(data) } diff --git a/codec_test.go b/codec_test.go index 6074400..dbe75ca 100644 --- a/codec_test.go +++ b/codec_test.go @@ -180,6 +180,13 @@ func TestUnmarshalJSON(t *testing.T) { } } +func TestUnmarshalJSONNull(t *testing.T) { + var test Test + err := json.Unmarshal([]byte(`{"price": null}`), &test) + require.NoError(t, err) + require.True(t, test.Test.IsZero()) +} + func TestMarshalBinary(t *testing.T) { testcases := []struct { in string