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/

相关文章:

pointers - 在方法中初始化一个 nil 指针结构

go - net.IP 没有实现 net.Addr(缺少网络方法)

go - 如何在 Golang 中查看 GOGC 值?

json - 如何使用 jsonpb 将 JSON 解码为包含一个定义的 protobuf?

sockets - UDP ping - 尝试获取端口不可达错误

csv - 总结csv的内容

go - golang 的目的 deadline(time.Now()) 是什么?

go - 如何根据结构字段类型键入值?

sql - golang数据库开放函数歧义

Goroutine 输出到 channel 顺序固定吗?