golang 處理 json 結構體


首先 我們來看一下這個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)
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM