Answer the question
In order to leave comments, you need to log in
How to correctly convert types to int obtained from JSON?
It doesn't sound complicated, but in GO all numbers obtained from json.Unmarshal are of type float64.
What if I need to receive an int and write some kind of helper for this. To get directly from the "method" the value of the sent data in the request in the required format?
I climb into the encode / json documentation, I find the UseNumber () decoder method, which converts all numbers instead of float64 to the json.Number type, which in turn has several methods for converting to other types, but the types are again not the ones that are needed, only int64, Float64,string
func (c *Controller) GetInt(name string) (i int) {
if val, status := c.Params[name]; status {
switch val.(type) {
case json.Number:
i64, _ := val.(json.Number).Int64()
i = int(i64)
}
}
return
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question