我有一个来自 api 的 json 响应,如 map[message:Login Success. userid:1]
服务器:
c.JSON(200, gin.H{"message": "Login Success.", "userid": 1})
客户:
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
}
但是 userID, ok := result["userid"].(int)
总是失败。我什至尝试过使用:
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")
}
它只是给了我未知。为什么整数不被当作整数?
它看起来像是将值视为 float64
。
最佳答案
在这里您可以找到为什么您得到的是 float64
而不是 int
的解释:
检查 Decode 的文档
See the documentation for Unmarshal for details about the conversion of JSON into a Go value.
还有see
To unmarshal JSON into an interface value, Unmarshal stores one of these in the interface value:
float64, for JSON numbers
关于go - JSON 解码值被视为 float64 而不是 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55436628/