douweiduo7526 2019-03-30 23:40
浏览 244
已采纳

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

I have a json response from a api as map[message:Login Success. userid:1]

Server:

c.JSON(200, gin.H{"message": "Login Success.", "userid": 1})

Client:

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
}

But userID, ok := result["userid"].(int) always fails. I've even tried using:

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")      
}

And it just gave me unknown. Why is the integer not being taken as integer?


It looks like its treating the value as float64.

  • 写回答

1条回答 默认 最新

  • duanpengya7074 2019-03-31 00:09
    关注

    Here you can find the explanation why you are getting float64 and not int:

    Check doc for Decode

    See the documentation for Unmarshal for details about the conversion of JSON into a Go value.

    And there see

    To unmarshal JSON into an interface value, Unmarshal stores one of these in the interface value:

    float64, for JSON numbers
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器