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

时间:2019-03-30 23:40:41

标签: go

我有一个来自map[message:Login Success. userid:1]的api的json响应

服务器:

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

1 个答案:

答案 0 :(得分:3)

在这里您可以找到解释说明为什么获得float64而不是int的原因:

检查文档中的Decode

  

有关将JSON转换为Go值的详细信息,请参阅Unmarshal的文档。

还有see

  

要将JSON解组为接口值,Unmarshal将其中之一存储在接口值中:

float64, for JSON numbers
相关问题