【问题标题】:Golang howto unmarshal nested structure into a slice of structsGolang 如何将嵌套结构解组为一片结构
【发布时间】:2019-04-13 18:43:38
【问题描述】:

如何在 Golang 中解组此 json 代码。我有主机名和 IP 地址,但没有 snmpV1 部分:

[
    {
        "hostname" : "myserver",
        "ipaddress" : "127.0.0.1",
        "snmpVersion" : 1,
        "snmpV1" : {
            "community" : "public"
        }
    }
]

我有以下结构:

type Device struct {
    Hostname string `json: "hostname"`
    Ipaddress string `json:"ipaddress"`
    SnmpVersion int `json:"snmpVersion"`
    SnmpV1cred struct {
        Community string `json: "community"`
    } `json: "snmpV1"`
    SnmpV3cred struct {
        secName string `json: "secName"`
        authPassword string `json: "authPassword"`
        AuthProto string `json: "authProtocol"`
        PrivPassword string `json: "privPassword"`
        PrivProto string `json: "priveProtocol"`
        secLevel string `json: "secLevel"`
    } `json: "snmpV3"`
}

然后我使用以下方法解组:

deviceList := []Device{}
buffer, err := ioutil.ReadFile(deviceFile)
if err != nil {
    logger.Fatal(err)
}

err = json.Unmarshal(buffer, &deviceList)

但是我只能通过 fmt.Println 得到这个: [{myserver 127.0.0.1 1 {} { }}]

【问题讨论】:

    标签: json go


    【解决方案1】:

    删除字段标签中:" 之间的空格。 Export所有字段。

    type Device struct {
        Hostname    string `json:"hostname"`
        Ipaddress   string `json:"ipaddress"`
        SnmpVersion int    `json:"snmpVersion"`
        SnmpV1cred  struct {
            Community string `json:"community"`
        } `json:"snmpV1"`
        SnmpV3cred struct {
            SecName      string `json:"secName"`
            AuthPassword string `json:"authPassword"`
            AuthProto    string `json:"authProtocol"`
            PrivPassword string `json:"privPassword"`
            PrivProto    string `json:"priveProtocol"`
            SecLevel     string `json:"secLevel"`
        } `json:"snmpV3"`
    }
    

    go vet 命令报告这些错误。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-25
      • 1970-01-01
      • 1970-01-01
      • 2018-04-17
      • 1970-01-01
      • 2021-12-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多