Skip to content

Commit d684e27

Browse files
authored
Support number/string agnostic JSON decoding (#24)
1 parent be20d5d commit d684e27

File tree

2 files changed

+36
-4
lines changed

2 files changed

+36
-4
lines changed

amount.go

+10-4
Original file line numberDiff line numberDiff line change
@@ -315,16 +315,22 @@ func (a Amount) MarshalJSON() ([]byte, error) {
315315
// UnmarshalJSON implements the json.Unmarshaler interface.
316316
func (a *Amount) UnmarshalJSON(data []byte) error {
317317
aux := struct {
318-
Number string `json:"number"`
319-
CurrencyCode string `json:"currency"`
318+
Number json.RawMessage `json:"number"`
319+
CurrencyCode string `json:"currency"`
320320
}{}
321321
err := json.Unmarshal(data, &aux)
322322
if err != nil {
323323
return err
324324
}
325+
326+
var auxNumber string
327+
if err = json.Unmarshal(aux.Number, &auxNumber); err != nil {
328+
auxNumber = string(aux.Number)
329+
}
330+
325331
number := apd.Decimal{}
326-
if _, _, err := number.SetString(aux.Number); err != nil {
327-
return InvalidNumberError{aux.Number}
332+
if _, _, err := number.SetString(auxNumber); err != nil {
333+
return InvalidNumberError{auxNumber}
328334
}
329335
if aux.CurrencyCode == "" || !IsValid(aux.CurrencyCode) {
330336
return InvalidCurrencyCodeError{aux.CurrencyCode}

amount_test.go

+26
Original file line numberDiff line numberDiff line change
@@ -812,6 +812,32 @@ func TestAmount_UnmarshalJSON(t *testing.T) {
812812
t.Errorf("got %T, want currency.InvalidNumberError", err)
813813
}
814814

815+
d = []byte(`{"number": {"key": "value"}, "currency": "USD"}`)
816+
err = json.Unmarshal(d, unmarshalled)
817+
if e, ok := err.(currency.InvalidNumberError); ok {
818+
if e.Number != `{"key": "value"}` {
819+
t.Errorf(`got %v, "want {"key": "value"}"`, e.Number)
820+
}
821+
wantError := `invalid number "{\"key\": \"value\"}"`
822+
if e.Error() != wantError {
823+
t.Errorf("got %v, want %v", e.Error(), wantError)
824+
}
825+
} else {
826+
t.Errorf("got %T, want currency.InvalidNumberError", err)
827+
}
828+
829+
d = []byte(`{"number":3.45,"currency":"USD"}`)
830+
err = json.Unmarshal(d, unmarshalled)
831+
if err != nil {
832+
t.Errorf("unexpected error: %v", err)
833+
}
834+
if unmarshalled.Number() != "3.45" {
835+
t.Errorf("got %v, want 3.45", unmarshalled.Number())
836+
}
837+
if unmarshalled.CurrencyCode() != "USD" {
838+
t.Errorf("got %v, want USD", unmarshalled.CurrencyCode())
839+
}
840+
815841
d = []byte(`{"number":"3.45","currency":"usd"}`)
816842
err = json.Unmarshal(d, unmarshalled)
817843
if e, ok := err.(currency.InvalidCurrencyCodeError); ok {

0 commit comments

Comments
 (0)