-
Notifications
You must be signed in to change notification settings - Fork 46
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Support number/string agnostic JSON decoding #24
Conversation
Thanks! This is definitely worth a try. The tests aren't passing though, we need to make sure MarshalJSON() still returns a string, while Unmarshal can accept both a string and a number. |
0120d9c
to
cbf5aa7
Compare
cbf5aa7
to
c1bbd0d
Compare
I reverted Instead, we can use |
Using json.RawMessage makes sense, but I don't think we can unmarshal to a string after that, that will still fail if the input was a number. I suggest something like this: aux := struct {
Number json.RawMessage `json:"number"`
CurrencyCode string `json:"currency"`
}{}
if err := json.Unmarshal(data, &aux); err != nil {
return err
}
var jsonNumber json.Number
if err := json.Unmarshal(aux.Number, &jsonNumber); err != nil {
if strings.HasPrefix(err.Error(), "json: invalid number") {
return InvalidNumberError{strings.Trim(string(aux.Number), `"`)}
} else {
return err
}
}
number := apd.Decimal{}
if _, _, err := number.SetString(jsonNumber.String()); err != nil {
return InvalidNumberError{jsonNumber.String()}
}
if aux.CurrencyCode == "" || !IsValid(aux.CurrencyCode) {
return InvalidCurrencyCodeError{aux.CurrencyCode}
} |
I added the test case you suggested, and all the tests appear to pass for me.
Currently, the PR does this:
In the first case, My only concern with your suggested solution is that it depends on the stability of the error text from the Thanks for your help on this! |
Sorry for coming back to this so late. Your version is definitely cleaner, so proceeding. Thank you! |
For certain applications, it's helpful to be able to decode a currency object from either a JSON string or number.
This PR uses the stdlib
json.Number
, instead of string, to handle either case gracefully.