簡體   English   中英

Golang howto將嵌套結構解組成一片結構

[英]Golang howto unmarshal nested structure into a slice of structs

我如何在Golang中解析這個json代碼。 我有主機名和ipaddress但不是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 {} {}}]

刪除:"在字段標記之間的空格。 導出所有字段。

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命令報告這些錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM