Skip to content

Commit

Permalink
feat: add support for JSON null value (#14)
Browse files Browse the repository at this point in the history
  • Loading branch information
mdawar authored Oct 19, 2024
1 parent 5d3d0ff commit cf139d3
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 0 deletions.
9 changes: 9 additions & 0 deletions codec.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package udecimal

import (
"bytes"
"database/sql"
"database/sql/driver"
"encoding"
Expand Down Expand Up @@ -236,13 +237,21 @@ 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.
if len(data) >= 2 && data[0] == '"' && data[len(data)-1] == '"' {
data = data[1 : len(data)-1]
}

// null value.
if bytes.Equal(data, nullValue) {
return nil
}

return d.UnmarshalText(data)
}

Expand Down
7 changes: 7 additions & 0 deletions codec_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit cf139d3

Please sign in to comment.