You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

52 lines
918 B

package main
import (
"encoding/json"
"fmt"
)
type Student struct {
ID int
Gender string
Name string
}
type Class struct {
Title string
Student []*Student
}
func main() {
c := &Class{
Title: "101",
Student: make([]*Student, 0, 200),
}
for i := 0; i < 10; i++ {
stu := &Student{
ID: i,
Gender: "男",
Name: fmt.Sprintf("stu%02d", i),
}
c.Student = append(c.Student, stu)
}
//for _, v := range c.Student {
// fmt.Printf("%#v\n", v)
//}
data, err := json.Marshal(c)
if err != nil {
fmt.Println("json marshal failed")
return
}
fmt.Printf("JSON:\n %s\n", data)
str := `{"Title":"101","Student":[{"ID":0,"Gender":"男","Name":"stu00"},{"ID":1,"Gender":"男","Name":"stu01"}]}`
c1 := &Class{}
err = json.Unmarshal([]byte(str), c1)
if err != nil {
fmt.Println("json unmarshal failed")
return
}
for _, v := range c1.Student {
fmt.Printf("%#v\n", v)
}
}