This commit is contained in:
davidnewhall2 2019-11-29 23:00:31 -08:00
parent 2ce0e76c85
commit d6f1ca10c7
2 changed files with 6 additions and 4 deletions

View File

@ -93,18 +93,16 @@ func (f *FlexInt) UnmarshalJSON(b []byte) error {
case float64:
f.Val = i
f.Txt = strconv.FormatFloat(i, 'f', -1, 64)
return nil
case string:
f.Txt = i
f.Val, _ = strconv.ParseFloat(i, 64)
return nil
case nil:
f.Txt = "0"
f.Val = 0
return nil
default:
return fmt.Errorf("cannot unmarshal to FlexInt: %s", b)
}
return nil
}
// FlexBool provides a container and unmarshalling for fields that may be

View File

@ -15,10 +15,11 @@ func TestFlexInt(t *testing.T) {
Seven FlexInt `json:"seven"`
Auto FlexInt `json:"auto"`
Channel FlexInt `json:"channel"`
Nil FlexInt `json:"nil"`
}
var r testReply
// test unmarshalling the custom type three times with different values.
a.Nil(json.Unmarshal([]byte(`{"five": "5", "seven": 7, "auto": "auto"}`), &r))
a.Nil(json.Unmarshal([]byte(`{"five": "5", "seven": 7, "auto": "auto", "nil": null}`), &r))
// test number in string.
a.EqualValues(5, r.Five.Val)
@ -33,4 +34,7 @@ func TestFlexInt(t *testing.T) {
a.NotNil(json.Unmarshal([]byte(`{"channel": {}}`), &r),
"a non-string and non-number must produce an error.")
a.EqualValues(0, r.Channel.Val)
// test null.
a.EqualValues(0, r.Nil.Val)
a.EqualValues("0", r.Nil.Txt)
}