合规国际互联网加速 OSASE为企业客户提供高速稳定SD-WAN国际加速解决方案。 广告
>[info] json * **引入** ~~~ import ( json "github.com/json-iterator/go" ) ~~~ * **JSON序列化:结构体 -> JSON格式的字符串** ~~~ package main import ( "fmt" json "github.com/json-iterator/go" ) // Student 学生 type Student struct { ID int Gender string Name string } // Class 班级 type Class struct { Title string Students []*Student } func main() { c := &Class{ Title: "101", Students: make([]*Student, 0, 200), } for i := 0; i < 3; i++ { stu := &Student{ Name: fmt.Sprintf("stu%02d", i), Gender: "男", ID: i, } c.Students = append(c.Students, stu) } //JSON序列化:结构体-->JSON格式的字符串 data, err := json.Marshal(c) if err != nil { fmt.Println("json marshal failed") return } fmt.Printf("%s\n", data) } ~~~ * **JSON反序列化:JSON格式的字符串 -> 结构体** ~~~ package main import ( "fmt" json "github.com/json-iterator/go" ) // Student 学生 type Student struct { ID int Gender string Name string } // Class 班级 type Class struct { Title string Students []*Student } func main() { str := `{"Title":"101","Students":[{"ID":0,"Gender":"男","Name":"stu00"},{"ID":1,"Gender":"男","Name":"stu01"},{"ID":2,"Gender":"男","Name":"stu02"}]}` c1 := &Class{} err := json.Unmarshal([]byte(str), c1) if err != nil { fmt.Println("json unmarshal failed!") } // &main.Class{Title:"101", Students:[]*main.Student{(*main.Student)(0xc00001fbf0), (*main.Student)(0xc00001fc20), (*main.Student)(0xc00001fc50)}} fmt.Printf("%#v\n", c1) } ~~~