douwen1901
2019-04-13 18:43 阅读 16

Golang Howto将嵌套结构解组为一片结构

How do I unMarshal this json code in Golang. I have the hostname and ipaddress but not the snmpV1 part:

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

I have the following struct:

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

Then I unmarshal using:

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

err = json.Unmarshal(buffer, &deviceList)

However I only get this with a fmt.Println: [{myserver 127.0.0.1 1 {} { }}]

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

1条回答 默认 最新

  • 已采纳
    dpqmu84646 dpqmu84646 2019-04-13 19:04

    Remove spaces between : and " in field tags. Export all fields.

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

    The go vet command reports these errors.

    点赞 评论 复制链接分享

相关推荐