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)
}

猜你喜欢

转载自www.cnblogs.com/feiquan/p/11468792.html