Skip to content

Commit

Permalink
Add null support to UnmarshalJSON (#58)
Browse files Browse the repository at this point in the history
Unmarshal null into zero value
  • Loading branch information
klokare authored and victorquinn committed Aug 16, 2017
1 parent 3c69277 commit b9ab2bc
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 8 deletions.
6 changes: 5 additions & 1 deletion decimal.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ func New(value int64, exp int32) Decimal {
func NewFromBigInt(value *big.Int, exp int32) Decimal {
return Decimal{
value: big.NewInt(0).Set(value),
exp: exp,
exp: exp,
}
}

Expand Down Expand Up @@ -615,6 +615,10 @@ func (d Decimal) Truncate(precision int32) Decimal {

// UnmarshalJSON implements the json.Unmarshaler interface.
func (d *Decimal) UnmarshalJSON(decimalBytes []byte) error {
if string(decimalBytes) == "null" {
return nil
}

str, err := unquoteIfQuoted(decimalBytes)
if err != nil {
return fmt.Errorf("Error decoding string '%s': %s", decimalBytes, err)
Expand Down
28 changes: 21 additions & 7 deletions decimal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -231,20 +231,19 @@ func TestNewFromFloatWithExponent(t *testing.T) {
}
}


func TestNewFromBigIntWithExponent(t *testing.T) {
type Inp struct {
val *big.Int
exp int32
exp int32
}
tests := map[Inp]string{
Inp{big.NewInt(123412345),-3}: "123412.345",
Inp{big.NewInt(2234), -1}: "223.4",
Inp{big.NewInt(323412345), 1}: "3234123450",
Inp{big.NewInt(123412345), -3}: "123412.345",
Inp{big.NewInt(2234), -1}: "223.4",
Inp{big.NewInt(323412345), 1}: "3234123450",
Inp{big.NewInt(423412345), 0}: "423412345",
Inp{big.NewInt(52341235), -5}: "523.41235",
Inp{big.NewInt(623412345),-6}: "623.412345",
Inp{big.NewInt(723412345),-7}: "72.3412345",
Inp{big.NewInt(623412345), -6}: "623.412345",
Inp{big.NewInt(723412345), -7}: "72.3412345",
}

// add negatives
Expand Down Expand Up @@ -299,6 +298,21 @@ func TestJSON(t *testing.T) {
}
}

func TestUnmarshalJSONNull(t *testing.T) {
var doc struct {
Amount Decimal `json:"amount"`
}
docStr := `{"amount": null}`
err := json.Unmarshal([]byte(docStr), &doc)
if err != nil {
t.Errorf("error unmarshaling %s: %v", docStr, err)
} else if !doc.Amount.Equal(Zero) {
t.Errorf("expected Zero, got %s (%s, %d)",
doc.Amount.String(),
doc.Amount.value.String(), doc.Amount.exp)
}
}

func TestBadJSON(t *testing.T) {
for _, testCase := range []string{
"]o_o[",
Expand Down

0 comments on commit b9ab2bc

Please sign in to comment.