[英]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.