我是 RTFMing ,特别是关于解码任意围棋数据的部分。基于该部分,我编写了以下测试程序
var f interface{}
json.Unmarshal(
[]byte(`{"Name":"Wednesday","Age":6,"Parents":["Gomez","Morticia"]}`), &f)
m := f.(map[string]interface{})
for k, v := range m {
switch vv := v.(type) {
case string:
fmt.Println(k, "is string", vv)
case int:
fmt.Println(k, "is int", vv)
case []interface{}:
fmt.Println(k, "is an array:")
for i, u := range vv {
fmt.Println(i, u)
}
default:
fmt.Println(k, "is of a type I don't know how to handle")
fmt.Println(" Type Is:", vv)
}
}
也就是说,我声明了一个空接口(interface)类型的变量。根据文档,我
use a type assertion to access f's underlying map[string]interface{}:
然后,我使用 range
对 map 的键/值对执行 for 循环。如果该值是字符串、整数或 []interface,程序会这样说。如果该值是另一种类型(默认情况),程序会说我不知道如何处理它。这几乎是手册中的逐字代码。
程序产生以下输出。
Name is string Wednesday
Age is of a type I don't know how to handle
Type Is: 6
Parents is an array:
0 Gomez
1 Morticia
也就是说——它正确地识别了字符串和数组的类型——出于某种原因,似乎解析的 6
的类型不是 int
-- 是 6。
所以——我想我的问题是 *为什么 v.(type)
在这里返回实际数字而不是 int
或我的问题是为什么这个问题是错误的?
最佳答案
JSON 数字是 double float ,因此 go 使用的默认类型是 float64
。您可以看到 json.Unmarshal
中列出的默认值文档。
关于json - Go 的 .(type) 在解码 JSON 时做一些意外的事情,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46836641/