go - 将 JSON 整数解码为空接口(interface)会导致错误的类型断言

标签 go go-interface

我有这个代码。我希望接口(interface)的类型断言为 int。但是,接口(interface)的类型改为 float64。谁能解释为什么会这样?规避它的最佳方法是什么。

package main

import (
    "fmt"
    "encoding/json"
)

type obj struct {
    X interface{}
}

func main() {
    var x int
    x = 5
    o := &obj {
        X: x,
    }
    b, _ := json.Marshal(o)
    var newObj obj
    json.Unmarshal(b, &newObj)
    if _, ok := newObj.X.(int); ok {
        fmt.Println("X is an int")
    } else if _, ok := newObj.X.(float64); ok {
        fmt.Println("X is a float64")
    } else {
        fmt.Println("This does not make any sense")
    }
}

此代码打印“X is a float64”。您可以在那里运行代码 https://play.golang.org/p/9L9unW8l3n

最佳答案

数字被编码为“Json 数字”Unmarshal 将 Json 数字解码为 float 。来自文档:

Marshal

Floating point, integer, and Number values encode as JSON numbers.

Unmarshal

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

bool, for JSON booleans float64, for JSON numbers string, for JSON strings []interface{}, for JSON arrays map[string]interface{}, for JSON objects nil for JSON null

关于go - 将 JSON 整数解码为空接口(interface)会导致错误的类型断言,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39152481/

相关文章:

go - 如何将我的资源拆分成多个文件

json - Golang解析JSON返回0

go - Go 中文件名的约定是什么?

go - 我通常可以为 Golang 结构指定方法吗?

从接口(interface)获取指向结构的指针?

go - unicode 按字面输出而不是 unicode

go - 正则表达式匹配字符串值并替换 golang 中的所有出现

pointers - 混淆函数参数中的指针、 slice 和接口(interface){}

go - GoLang 接口(interface)名称及其方法数的规则

Go接口(interface)返回类型