首先 我們來看一下這個json 字串
{ "resp": { "respCode": "000000", "respMsg": "成功", "app": { "appId": "xxxxxx" } } }
go 內置了json字串的解析包 "encoding/json"
接下來 就需要對結構體的定義了。
按照json庫的分析,其實每一個花括號就是一個結構體
那么拆解的結構體如下:
//代表最里層的結構體 type appInfo struct { Appid string `json:"appId"` } //代表第二層的結構體 type response struct { RespCode string `json:"respCode"` RespMsg string `json:"respMsg"` AppInfo appInfo `json:"app"` } type JsonResult struct { Resp response `json:"resp"` //代表最外層花括號的結構體 }
結構體的命名必須遵循第一個字母大寫,否則json庫會忽略掉該成員,
而后面的json:“xxx” xxx則需要和json字串里的名字相符合: 如最外層的 json:"**resp**"
和json字符串里的{“resp”一致
然后實際的代碼解析如下
package main import ( "fmt" "encoding/json" ) type appInfo struct { Appid string `json:"appId"` } type response struct { RespCode string `json:"respCode"` RespMsg string `json:"respMsg"` AppInfo appInfo `json:"app"` } type JsonResult struct { Resp response `json:"resp"` } func main() { jsonstr := `{"resp": {"respCode": "000000","respMsg": "成功","app": {"appId": "xxxxxx"}}}` var JsonRes JsonResult json.Unmarshal(body, &JsonRes) fmt.Println("after parse", JsonRes) }