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

 

转载于:https://www.cnblogs.com/feiquan/p/11468792.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值