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

标签 go

我有一个来自 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/

相关文章:

http - 如何检查错误是否是Go中的tls握手超时

google-app-engine - Golang lua-script 就像在 GAE 上运行

node.js - NodeJS vs Golang for REST API 并用它实现后端

unit-testing - 需要帮助查明中间件测试(Golang)中零引用错误的原因

go - 与多个包共享全局定义的 db conn

linux - 挂载点归属

ios - 如何使用 NSData 在我的 Golang 服务器上读取我从 iOS 发布的 JSON?

assembly - Go 没有链接我的程序集 : undefined external function

pointers - 存储指向堆栈值的指针 (Golang)

json - 使用 golang JSON 解码 PubNub 消息