package main import ( "fmt" "encoding/json" ) type addr struct { Province string City string } type stu struct { Name string Age int Addr addr } funcmain(){ var xm = stu{Name:"xiaoming", Age:18, Addr:addr{Province:"Hunan",City:"ChangSha"}} js, err := json.Marshal(xm) if err != nil{ fmt.Println(err) return } fmt.Println(string(js)) //输出{"Name":"xiaoming","Age":18,"Addr":{"Province":"Hunan","City":"ChangSha"}} }
package main import ( "fmt" "encoding/json" ) type addr struct { Province string City string } type stu struct { Name string Age int Addr addr } funcmain(){ js := `{"Age":18,"name":"xiaoming","Addr":{"Province":"Hunan","City":"ChangSha"}}`//name是小写 var xm stu err := json.Unmarshal([]byte(js), &xm) if err != nil{ fmt.Println(err) return } fmt.Println(xm) //输出{xiaoming 18 {Hunan ChangSha}} }
package main import ( "fmt" "encoding/json" ) type addr struct { Province string`json:"province"`//转化后对应字段的json名为province City string`json:"city"` } type stu struct { Name string`json:"name"` Age int`json:"age"` Addr addr `json:"addr"` } funcmain(){ var xm = stu{Name: "xiaoming", Age: 18, Addr:addr{Province:"Hunan",City:"ChangSha"}} js, err := json.Marshal(xm) if err != nil{ fmt.Println(err) return } fmt.Println(string(js)) var xxm stu err = json.Unmarshal(js, & xxm) fmt.Println(xxm) }
package main import ( "fmt" "encoding/json" ) type addr struct { Province string City string } type stu struct { Name string Age int Addr addr } funcmain(){ var xm = stu{Name:"xiaoming", Age:18, Addr:addr{Province:"Hunan",City:"ChangSha"}} js, err := json.Marshal(xm) if err != nil{ fmt.Println(err) return } fmt.Println(string(js)) //输出{"Name":"xiaoming","Age":18,"Addr":{"Province":"Hunan","City":"ChangSha"}} }
package main import ( "fmt" "encoding/json" ) type addr struct { Province string City string } type stu struct { Name string Age int Addr addr } funcmain(){ js := `{"Age":18,"name":"xiaoming","Addr":{"Province":"Hunan","City":"ChangSha"}}`//name是小写 var xm stu err := json.Unmarshal([]byte(js), &xm) if err != nil{ fmt.Println(err) return } fmt.Println(xm) //输出{xiaoming 18 {Hunan ChangSha}} }
package main import ( "fmt" "encoding/json" ) type addr struct { Province string`json:"province"`//转化后对应字段的json名为province City string`json:"city"` } type stu struct { Name string`json:"name"` Age int`json:"age"` Addr addr `json:"addr"` } funcmain(){ var xm = stu{Name: "xiaoming", Age: 18, Addr:addr{Province:"Hunan",City:"ChangSha"}} js, err := json.Marshal(xm) if err != nil{ fmt.Println(err) return } fmt.Println(string(js)) var xxm stu err = json.Unmarshal(js, & xxm) fmt.Println(xxm) }