Add JSON unmarshallers for numeric types from util (#83)

Uint160, Uint256, Fixed8 now have UnmarshalJSON method.
This commit is contained in:
Evgenii Stratonikov 2018-05-09 08:20:16 +03:00 committed by Anthony De Meulemeester
parent 35551282b0
commit 1d9045877c
8 changed files with 110 additions and 4 deletions

View file

@ -2,6 +2,7 @@ package util
import (
"bytes"
"encoding/json"
"errors"
"strconv"
"strings"
@ -49,7 +50,8 @@ func NewFixed8(val int) Fixed8 {
return Fixed8(decimals * val)
}
// Fixed8DecodeString
// Fixed8DecodeString parses s which must be a fixed point number
// with precision up to 10^-8
func Fixed8DecodeString(s string) (Fixed8, error) {
parts := strings.SplitN(s, ".", 2)
ip, err := strconv.Atoi(parts[0])
@ -68,3 +70,24 @@ func Fixed8DecodeString(s string) (Fixed8, error) {
}
return Fixed8(ip*decimals + fp), nil
}
// UnmarshalJSON implements the json unmarshaller interface.
func (f *Fixed8) UnmarshalJSON(data []byte) error {
var s string
if err := json.Unmarshal(data, &s); err == nil {
p, err := Fixed8DecodeString(s)
if err != nil {
return err
}
*f = p
return nil
}
var fl float64
if err := json.Unmarshal(data, &fl); err != nil {
return err
}
*f = Fixed8(decimals * fl)
return nil
}