//project main.gopackage mainimport ( "encoding/json" "fmt")func main() { fmt.Println(help()) b := []byte(`{ "Title": "Go语言编程", "Authors": ["XuShiwei", "HughLv", "Pandaman", "GuaguaSong", "HanTuo", "BertYuan", "XuDaoli"], "Publisher": "ituring.com.cn", "IsPublished": true, "Price": 9.99, "Sales": 1000000 }`) var r interface{} err := json.Unmarshal(b, &r) fmt.Println("r = ", r, "err = ", err, "\n") gobook, ok := r.(map[string]interface{}) if ok { for k, v := range gobook { switch v2 := v.(type) { case string: fmt.Println(k, "is string", v2) case int: fmt.Println(k, "is int", v2) case bool: fmt.Println(k, "is bool", v2) case []interface{}: fmt.Println(k, "is an array:") for i, iv := range v2 { fmt.Println(i, iv) } default: fmt.Println(k, "is another type not handle yet") } } }}func help() string { return ` Go内建这样灵活的类型系统,向我们传达了一个很有价值的信息:空接口是通用类型。如 果要解码一段未知结构的JSON,只需将这段JSON数据解码输出到一个空接口即可。在解码JSON 数据的过程中, JSON数据里边的元素类型将做如下转换: JSON中的布尔值将会转换为Go中的bool类型; 数值会被转换为Go中的float64类型; 字符串转换后还是string类型; JSON数组会转换为[]interface{}类型; JSON对象会转换为map[string]interface{}类型; null值会转换为nil `}
输出:
Go内建这样灵活的类型系统,向我们传达了一个很有价值的信息:空接口是通用类型。如 果要解码一段未知结构的JSON,只需将这段JSON数据解码输出到一个空接口即可。在解码JSON 数据的过程中, JSON数据里边的元素类型将做如下转换: JSON中的布尔值将会转换为Go中的bool类型; 数值会被转换为Go中的float64类型; 字符串转换后还是string类型; JSON数组会转换为[]interface{}类型; JSON对象会转换为map[string]interface{}类型; null值会转换为nil r = map[IsPublished:true Price:9.99 Sales:1e+06 Title:Go语言编程 Authors:[XuShiwei HughLv Pandaman GuaguaSong HanTuo BertYuan XuDaoli] Publisher:ituring.com.cn] err =Title is string Go语言编程Authors is an array:0 XuShiwei1 HughLv2 Pandaman3 GuaguaSong4 HanTuo5 BertYuan6 XuDaoliPublisher is string ituring.com.cnIsPublished is bool truePrice is another type not handle yetSales is another type not handle yet