string to json
// 轉化string變成json
// 第二個參數需要是一個結構體變量
json.Unmarshal([]byte, interface{})
定義要轉化成json的結構體的時候,要根據json里面會包含的內容來定義結構體,且要加tag
如:
{
"name": "xiaoming",
"postion": "China",
"studentId": "20020200202"
}
這時候結構體就要定義為:
// 大寫是為了可以被外部引用
type student struct{
Name string `json:"name"`
Postions string `json:"postion"`
StudentId string `json:"studentId"`
}
當遇到json對象是對層嵌套時
如:
{
"name": "xiaoming",
"postion": "China",
"studentId": "20020200202",
"friend":{
"name": "xiaogang",
"postion": "China"
}
}
可以使用:
// 大寫是為了可以被外部引用
type student struct{
Name string `json:"name"`
Postions string `json:"postion"`
StudentId string `json:"studentId"`
Friend map[string]interface{} `json:"friend"`
}
若遇到更多層嵌套可以多次使用這種方式多層解構
json to string
// 通常傳入的是一個map, 會返回一個[]byte和一個error
json.Marshal(interface{})