Golang 使用 JSON unmarshal 数字到 interface{} 数字变成 float64 类型(类型断言)
JSON unmarshal 数字到 interface{} 数字变成 float64 类型
使用 Golang 解析 JSON 格式数据时,若以 interface{} 接收数字成员,则会按照下列规则进行解析,可见
使用 Golang 对 JSON 结构进行解析(unmarshal)时,JSON 结构中的数字会被解析为 float64 类型:
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
如果要转换为整型,可用类型断言,如下所示:
int( a["id"].(float64) ) // 将 interface{} 类型的 “id” 键申明为 float64 类型,再转换为 int 型
bye the way
Golang中的类型断言用于取出 interface 类型中的值,用法是 变量名.(类型), 变量当前必须是 interface 类型,通过类型断言,可以获得类型强转后的对象,这个断言可以有一个返回值,也可以有两个返回值,如果是一个返回值,返回对应类型的变量,如果有2个返回值,第一个返回值还是强转后的结果,第二个是断言书否成功,即变量是否是该类型的变量
i := x.(int) // 如果是一个返回值,返回对应类型的变量
v, ok := x.(T) // 如果有2个返回值,第一个返回值还是强转后的结果,第二个是断言书否成功,即变量是否是该类型的变量
注意:如果是一个返回值,返回对应类型的变量,如果断言失败,也就是强转失败,则直接报 panic
func main() {
x := 1
typeAssert(x)
}
func typeAssert(a interface{}) {
i := a.(string) // panic: interface conversion: interface {} is int, not string
fmt.Printf("i=", i)
}
interface{} 转换成 int 的一个通用函数
func GetInterfaceToInt(t1 interface{}) int {
var t2 int
switch t1.(type) {
case uint:
t2 = int(t1.(uint))
break
case int8:
t2 = int(t1.(int8))
break
case uint8:
t2 = int(t1.(uint8))
break
case int16:
t2 = int(t1.(int16))
break
case uint16:
t2 = int(t1.(uint16))
break
case int32:
t2 = int(t1.(int32))
break
case uint32:
t2 = int(t1.(uint32))
break
case int64:
t2 = int(t1.(int64))
break
case uint64:
t2 = int(t1.(uint64))
break
case float32:
t2 = int(t1.(float32))
break
case float64:
t2 = int(t1.(float64))
break
case string:
t2, _ = strconv.Atoi(t1.(string))
break
default:
t2 = t1.(int)
break
}
return t2
}

浙公网安备 33010602011771号