golang,结构体与json相互转换

package main

import (
   "encoding/json"
   "fmt"
)

// go get -u github.com/gin-gonic/gin
// import "github.com/gin-gonic/gin"
type Class struct {
   Title    string    `json:"title"`
   Students []Student `json:"students"`
}
type Student struct {
   Id   int    `json:"id"`
   Name string `json:"name"`
   Age  int    `json:"age"`
}

func toJson() {
   c1 := Class{
      Title:    "三年级一班",
      Students: make([]Student, 0),
   }
   for i := 0; i < 10; i++ {
      s1 := Student{
         Id:   i,
         Name: fmt.Sprintf("name%v", i),
         Age:  18,
      }
      c1.Students = append(c1.Students, s1)
   }

   fmt.Println("----------------------------")
   fmt.Printf("%#v", c1)
   strC, err := json.Marshal(c1)
   if err != nil {

   }
   fmt.Println(string(strC))
   toStruct(string(strC))
}
func toStruct(jsonStr string) {
   var c1 Class
   err := json.Unmarshal([]byte(jsonStr), &c1)
   if err != nil {
      fmt.Println(err)
   }
   fmt.Printf("%#v", c1)
}

func main() {
   toJson()

}

你可能感兴趣的:(golang,json)