import ( "encoding/json" "fmt" ) type Students struct { Name string Age int } type Class struct { ClassName string Stus []Students } func main() { stus := []Students{Students{Name: "李白", Age: 20}, Students{Name: "韩信", Age: 18}} clas := Class{ClassName: "计算机", Stus: stus} //序列化 data, err := json.Marshal(clas) if err != nil { fmt.Println("错误信息:", err) } fmt.Println("序列化数据为:", data) fmt.Println("json数据为:", string(data)) //反序列化为 var cla Class //可以使用数数组进行序列化,提高序列化效率 err2 := json.Unmarshal([]byte(data), &cla) if err2 != nil { fmt.Println("错误信息:", err2) } fmt.Println("反序列数据:", cla) }
"encoding/json" "fmt" ) type Students struct { Name string Age int } type Class struct { ClassName string Stus []Students } func main() { stus := []Students{Students{Name: "李白", Age: 20}, Students{Name: "韩信", Age: 18}} clas := Class{ClassName: "计算机", Stus: stus} //序列化 data, err := json.Marshal(clas) if err != nil { fmt.Println("错误信息:", err) } fmt.Println("序列化数据为:", data) fmt.Println("json数据为:", string(data)) //反序列化为 var cla Class //可以使用数数组进行序列化,提高序列化效率 err2 := json.Unmarshal([]byte(data), &cla) if err2 != nil { fmt.Println("错误信息:", err2) } fmt.Println("反序列数据:", cla) }
go序列化基本操作