Skip to content

Instantly share code, notes, and snippets.

@ssksameer56
Created November 29, 2022 10:26
Show Gist options
  • Save ssksameer56/64aa6b887bc68a70febbeae8a0d9ac27 to your computer and use it in GitHub Desktop.
Save ssksameer56/64aa6b887bc68a70febbeae8a0d9ac27 to your computer and use it in GitHub Desktop.
Custom Unmarshal functions to support floats and strings interchangabely.
//https://stackoverflow.com/questions/73573695/go-custom-unmarshaler-string-to-float
type CustomFloat float64
type CustomInt int64
func (c *CustomFloat) UnmarshalJSON(b []byte) error {
var s interface{}
if err := json.Unmarshal(b, &s); err != nil {
return err
}
switch v := s.(type) {
case float64:
*c = CustomFloat(v)
case string:
x, _ := strconv.ParseFloat(v, 64)
*c = CustomFloat(x)
}
return nil
}
func (c *CustomInt) UnmarshalJSON(b []byte) error {
var s interface{}
if err := json.Unmarshal(b, &s); err != nil {
return err
}
switch v := s.(type) {
case float64:
i := int(v)
*c = CustomInt(i)
case string:
x, _ := strconv.ParseInt(v, 10, 64)
*c = CustomInt(x)
}
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment