// code_032_json_unmarshal_to_interface project main.go
package main
import (
"encoding/json"
"fmt"
)
func main() {
b := []byte(`{
"company":"tianmei",
"subjects":[
"Go",
"C++",
"Python",
"Test"
],
"isok":true,
"price":666.666
}`)
//备注:subjects:["Test",]后面没有元素了,还有逗号会报错的。
var t interface{}
err := json.Unmarshal(b, &t)
if err != nil {
fmt.Println("json err:", err)
}
fmt.Println(t)
//使用断言判断类型
m := t.(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 float64:
fmt.Println(k, "is float64", vv)
case bool:
fmt.Println(k, "is bool", vv)
case []interface{}: //slice类型的元素为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 to handle")
}
}
}
©著作权归作者所有:来自51CTO博客作者ck_god的原创作品,如需转载,请注明出处,否则将追究法律责任