Created
November 29, 2022 10:26
-
-
Save ssksameer56/64aa6b887bc68a70febbeae8a0d9ac27 to your computer and use it in GitHub Desktop.
Custom Unmarshal functions to support floats and strings interchangabely.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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