JSON解码值被视为float64而不是int

JSON解码值被视为float64而不是int

问题描述:

I have a json response from a api as map[message:Login Success. userid:1]

Server:

c.JSON(200, gin.H{"message": "Login Success.", "userid": 1})

Client:

var result map[string]interface{}
json.NewDecoder(resp.Body).Decode(&result)

msg, ok := result["message"].(string)
if !ok {
    msg = "Something went wrong."
}
userID, ok := result["userid"].(int)
if !ok {
    userID = 0
}

But userID, ok := result["userid"].(int) always fails. I've even tried using:

switch v := x.(type) {
case nil:
    fmt.Println("x is nil")          
case int: 
    fmt.Println("x is", v)           
case bool, string:
    fmt.Println("x is bool or string")
default:
    fmt.Println("type unknown")      
}

And it just gave me unknown. Why is the integer not being taken as integer?


It looks like its treating the value as float64.

Here you can find the explanation why you are getting float64 and not int:

Check doc for Decode

See the documentation for Unmarshal for details about the conversion of JSON into a Go value.

And there see

To unmarshal JSON into an interface value, Unmarshal stores one of these in the interface value:

float64, for JSON numbers