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)

}

 

 

你可能感兴趣的:(golang)