【发布时间】: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 {} { }}]
【问题讨论】: