我是RTFMing,特别是有关解码任意Go数据的部分。基于这一部分,我编写了以下测试程序
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)
}
}
也就是说,我声明了一个具有空接口类型的变量。根据文档,我
使用类型断言来访问f的基础map [string] interface {}:
然后,我range
用于对地图的键/值对进行for循环。如果该值是字符串,int或[]接口,则程序会这样说。如果该值是另一种类型(默认情况),则程序会说我不知道如何处理它。这几乎是手册中的逐字代码。
该程序产生以下输出。
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数字是双精度浮点数,因此go使用的默认类型是float64
。您可以在json.Unmarshal
文档中看到默认值。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句