我有一个来自 api 的 json 响应 map[message:Login Success. userid:1]
服务器:
c.JSON(200, gin.H{"message": "Login Success.", "userid": 1})
Run Code Online (Sandbox Code Playgroud)
客户:
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
}
Run Code Online (Sandbox Code Playgroud)
但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")
}
Run Code Online (Sandbox Code Playgroud)
它只是给了我未知。为什么整数不被视为整数?
看起来它把值当作float64.
Nik*_*Nik 16
在这里你可以找到为什么你得到float64而不是的解释int:
检查文档解码
有关将 JSON 转换为 Go 值的详细信息,请参阅 Unmarshal 的文档。
还有看到
要将 JSON 解组为接口值,Unmarshal 将其中之一存储在接口值中:
float64, for JSON numbers
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3849 次 |
| 最近记录: |