zoukankan      html  css  js  c++  java
  • 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)
    }
  • 相关阅读:
    20189222 《网络攻防技术》第一周作业
    apue.h 运行UNIX环境高编程序
    fflush()函数
    线性链表如何选择二级指针还是一级指针
    scanf()gets()fgets()区别
    淺談Coach思考模式
    Hello World
    C语言I博客作业04
    python模块:logging
    python模块:subprocess
  • 原文地址:https://www.cnblogs.com/feiquan/p/11468792.html
Copyright © 2011-2022 走看看