golang学习笔记 --- struct 嵌套

定义结构体

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"`
}

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

示例:

package main

import (
    "encoding/json"
    "fmt"
)

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"`
}

func main() {
    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"},
            }},
        },
    }

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

}

 

posted on 2020-07-28 13:05  清明-心若淡定  阅读(729)  评论(0编辑  收藏  举报