1. 程式人生 > >013-golang中json轉換成結構體或者map

013-golang中json轉換成結構體或者map

 

 

先拿一個json字串

jsonString := `{"name":"張三","age":20,"data":["男","未婚"]}`

 

func main() {

   jsonString := `{"name":"張三","age":20,"data":["男","未婚"]}`

   var stu Student

   err := json.Unmarshal([]byte(jsonString), &stu)

   if err!= nil {
      fmt.Println(err)
      return
   }

   fmt.Println(stu)

}

type Student struct {
   Name string   `json:"name"`
   Age  int      `json:"age"`
   Data []string `json:"data"`
}

 

用unmarshal方法哦

 

 

然後轉換成map

 

func main() {

   jsonString := `{"name":"張三","age":20,"data":["男","未婚"]}`

   m := make(map[string]interface{}, 4)

   err := json.Unmarshal([]byte(jsonString), &m)

   if err != nil {
      fmt.Println(err)
      return
   }

   fmt.Println(m)

}