zoukankan      html  css  js  c++  java
  • 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))
    
    }
  • 相关阅读:
    输入输出那些事
    NYOJ 20
    NYOJ 283
    HDU 1285
    HDU 2639(第K大背包)
    HDU 4288
    对Visual Studio C++ hash_map严谨一点的测试转载
    vc6,vc.net,vc7,vc8,vc9,c,c++,c#的区别与联系
    我在南大的七年刘末鹏
    慎用Visual Studio C++默认的hash_map转载
  • 原文地址:https://www.cnblogs.com/saryli/p/13390567.html
Copyright © 2011-2022 走看看