package main import ( "encoding/json" "fmt" ) type IT1 struct { Company string `json:"company"` Subjects []string `json:"subjects"` IsOk bool `json:"isok"` Price float64 `json:"price"` } type IT2 struct { Company string `json:"company"` } func main(){ jsonbuff :=`{ "company": "zhczGO", "isok": true, "price": 99, "subjects": [ "go", "fabric", "python", "Test" ] }` var temp IT1 err :=json.Unmarshal([]byte(jsonbuff),&temp) if err != nil{ fmt.Println("err=",err) return } //fmt.Println("temp=",temp) fmt.Printf("tmp=%+v\n",temp) var temp2 IT2 err = json.Unmarshal([]byte(jsonbuff),&temp2) if err != nil{ fmt.Println("err=",err) return } fmt.Printf("tmp2=%+v\n",temp2) }
package main import ( "encoding/json" "fmt" ) func main() { jsonbuff :=`{ "company": "zhczGO", "isok": true, "price": 99, "subjects": [ "go", "fabric", "python", "Test" ] }` //创建一个map m := make(map[string]interface{},4) err := json.Unmarshal([]byte(jsonbuff),&m) //一定要是地址 if err != nil{ fmt.Println("err=",err) return } fmt.Printf("m=%+v/n",m) //var str string //str = m["company"]//err 无法转换 //类型断言 for key,value := range m { switch data := value.(type) { case string: //str = data fmt.Printf("map[%s]的值类型为string,value=%s\n",key,data) case bool: fmt.Printf("map[%s]的值类型为bool,value=%v\n",key,data) case float64: fmt.Printf("map[%s]的值类型为float64,value=%f\n",key,data) case []string: fmt.Printf("map[%s]的值类型为[]string,value=%v\n",key,data) case []interface{}: fmt.Printf("map[%s]的值类型为interface{},value=%v\n",key,data) } } }
原文地址:https://www.cnblogs.com/dqh123/p/12076319.html
时间: 2024-10-03 09:59:33