先定义一对嵌套的结构体
//Student 学生type Student struct {ID int `json:"id"` // "ID"首字母大写是因为要序列化,必须大写,json包里才能访问。 `json:"id"`是让序列化后,"ID"用小写表示Gender string `json:"gender"`Name string `json:"name"`}
//Class 班级type Class struct {Title string `json:"title"`Students []*Student `json:"students"`}
序列化和反序列化
package main
import ("encoding/json""fmt")
func jsonSerialize(c *Class) string {// 对Class序列化data, err := json.Marshal(c) //序列化,返回data为bytes类型if err != nil {fmt.Println("Class序列化失败")return ""}return fmt.Sprintf("%s", data)}
func jsonDeserialize(s string) *Class {// 对Class反序列化c1 := Class{}err := json.Unmarshal([]byte(s), &c1) //传指针是为了能在json包里修改p2的值if err != nil {fmt.Println("Class反序列化失败")return nil}return &c1}
func main() {c := &Class{Title: "101",Students: make([]*Student, 0, 200),}for i := 0; i < 10; i++ {stu := &Student{Name: fmt.Sprintf("stu%02d", i),Gender: "男",ID: i,}c.Students = append(c.Students, stu)}// JSON序列化 c为内存地址fmt.Println(jsonSerialize(c))
//JSON反序列化str := `{"Title":"101","Students":[{"ID":0,"Gender":"男","Name":"stu00"},{"ID":1,"Gender":"男","Name":"stu01"},{"ID":2,"Gender":"男","Name":"stu02"}]}`c1 := jsonDeserialize(str)fmt.Println(c1.Students[0])fmt.Printf("%#v ", c1)}