package main import ( "encoding/json" "fmt" ) type Human struct { Name string Age int Rmb float64 Gender bool Hobbies []string } var jsonStr = `{ "name":"梅川酷子", "age":40, "rmb":12345.123, "gender":false, "hobbies":["抽烟","喝酒","烫头"] }` var jsonStr2 = `[ { "name":"梅川酷子", "age":40, "rmb":12345.123, "gender":false, "hobbies":["抽烟","喝酒","烫头"] }, { "name":"朴成幸", "age":40, "rmb":12345.123, "gender":false, "hobbies":["抽烟","喝酒","烫头"] } ]` //将json反序列化为Map func main051() { retMap := make(map[string]interface{}) err := json.Unmarshal([]byte(jsonStr), &retMap) if err != nil{ fmt.Println("反序列化失败,err=",err) return } fmt.Println(retMap) } //将json数组反序列化为切片 func main052() { retSlice := make([]map[string]interface{},0) err := json.Unmarshal([]byte(jsonStr2), &retSlice) if err != nil{ fmt.Println("反序列化失败,err=",err) return } fmt.Println(retSlice) } /*将json对象反序列化为结构体*/ func main053() { human := new(Human) err := json.Unmarshal([]byte(jsonStr), human) if err != nil{ fmt.Println("反序列化失败,err=",err) return } fmt.Println(human) } /*将json数组反序列化为切片嵌套结构体*/ func main() { retSlice := make([]Human, 0) err := json.Unmarshal([]byte(jsonStr2), &retSlice) if err != nil{ fmt.Println("反序列化失败,err=",err) return } fmt.Println(retSlice) }