美文网首页
golang 通过struct 构建多层嵌套的json数据

golang 通过struct 构建多层嵌套的json数据

作者: 会飞一下 | 来源:发表于2019-07-19 16:55 被阅读0次

此例用 微信的 设置菜单为例 底部三个菜单, 每个菜单里三个子菜单

定义结构体

type Btn struct{
  Name string  `json:"name"`
  Type string  `json:"type"`
  Url string   `json:"url"`
  Sub_button  []Btn  `json:"sub_button,omitempty"` //值为空时 直接忽略
  UnShow string `json"-"`  //忽略字段
}

type menu struct{
  Button []Btn   `json:"button"`
}

结构体赋值

jsonData := Menu{
    Button:[]Btn{
        {Name:"home",Type:"view",Url:"https://www.qq.com/auth"},
        {Name:"tool",Sub_button:[]Btn{
            {Name:"a1",Type:"view",Url:"https://www.qq.com/a1"},
            {Name:"a2",Type:"view",Url:"https://www.qq.com/a2"},
            {Name:"a3",Type:"view",Url:"https://www.qq.com/a3"},
        }},
        {Name:"other",Sub_button:[]Btn{
            {Name:"a1",Type:"view",Url:"https://www.qq.com/a1"},
            {Name:"a2",Type:"view",Url:"https://www.qq.com/a2"},
            {Name:"a3",Type:"view",Url:"https://www.qq.com/a3"},
        }},
    },
}

结构体转json

str,err := json.Marshal(jsonData)
if err != nil{
    panic(err)
}
fmt.println(string(str))

golang 模拟请求时, 传的参数是 map[string]interface{} 的类型, 所以这里需要将json数据处理成这种格式

param := map[string]interface{}{
    "button":[]Btn{
        {Name:"home",Type:"view",Url:"https://www.qq.com/auth"},
        {Name:"tool",Sub_button:[]Btn{
            {Name:"a1",Type:"view",Url:"https://www.qq.com/1"},
            {Name:"a1",Type:"view",Url:"https://www.qq.com/1"},
            {Name:"a1",Type:"view",Url:"https://www.qq.com/1"},
        }},
        {Name:"other",Sub_button:[]Btn{
            {Name:"a2",Type:"view",Url:"https://www.qq.com/a2"},
            {Name:"a2",Type:"view",Url:"https://www.qq.com/a2"},
            {Name:"a2",Type:"view",Url:"https://www.qq.com/a2"},
        }},
    },
}

*结构体命名需要大写 才会导出到json串中, 可以通过 struct tag 设置导出的别名, 可以通过 omitempty 忽略值为空的字段

相关文章

网友评论

      本文标题:golang 通过struct 构建多层嵌套的json数据

      本文链接:https://www.haomeiwen.com/subject/ppyslctx.html