我试图解组来自 vcenter rest api 的 json 响应。当简单地打印响应正文时,它看起来像下面的 o/p{"value":[{"memory_size_MiB":16384,"vm":"vm-10236","name":"Normal_Windows_192.168.1.10","power_state":"POWERED_OFF","cpu_count":8},{"memory_size_MiB":8192,"vm":"vm-10238","name":"Normal_Windows_192.168.1.11","power_state":"POWERED_OFF","cpu_count":4}]}我已经导出了结构和结构字段,但是像 memory_size_MiB、power_state、cpu_count 这样的字段没有被解组。打印结构时,它如下所示:-{Value:[{Mem:0 Vm:vm-10236 Name:Normal_Windows_192.168.1.10 Powerstat: Cpu:0} {Mem:0 Vm:vm-10238 Name:Normal_Windows_192.168.1.11 Powerstat: Cpu:0} {Mem:0 Vm:vm-10582 Name:Normal_Windows_192.168.1.12 Powerstat: Cpu:0}]}% 下面是我的 main.go package main import (... ) type SessionData struct { VmwareApiSessionId string `json:"value"` } //{"memory_size_MiB":16384,"vm":"vm-10236","name":"Normal_Windows_192.168.19.100","power_state":"POWERED_OFF","cpu_count":8} type Vm struct { Mem int `json: "memory_size_MiB"` Vm string `json: "vm"` Name string `json: "name"` Powerstat string `json: "power_state"` Cpu int `json: "cpu_count"` } //{Value:[{Mem:0 Vm:vm-10236 Name:Normal_Windows_192.168.1.10 Powerstat: Cpu:0} {Mem:0 Vm:vm-10238 Name:Normal_Windows_192.168.1.11 Powerstat: Cpu:0} {Mem:0 Vm:vm-10582 Name:Normal_Windows_192.168.1.12 Powerstat: Cpu:0}]} type ColVmList struct { Value []Vm `json: "value"` } func getVmList(sessid string,cli *http.Client) ColVmList { vms := ColVmList{} req,err:=http.NewRequest("GET","https://sandbox.vmware.local/rest/vcenter/vm",nil) req.Header.Add("vmware-api-session-id",sessid) resp,err := cli.Do(req) if err != nil { log.Fatal("Error %s", err) } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) fmt.Println(string(body)) err = json.Unmarshal([]byte(body),&vms) if err != nil { log.Fatal("error %s", err) } return vms }
1 回答
慕田峪9158850
TA贡献1794条经验 获得超7个赞
您的结构标签格式不正确。删除结构标签中json:的字符串和字符串之间的空格。"..."即它必须json:"..."不是json: "..."。
某些字段即使使用格式不正确的结构标记也能正确解组的原因是因为字段的名称与 json 属性名称匹配。
func main() {
data := []byte(`{"memory_size_MiB":16384}`)
var obj1 struct {
Mem int `json: "memory_size_MiB"`
}
if err := json.Unmarshal(data, &obj1); err != nil {
panic(err)
}
fmt.Println(obj1)
var obj2 struct {
Mem int `json:"memory_size_MiB"`
}
if err := json.Unmarshal(data, &obj2); err != nil {
panic(err)
}
fmt.Println(obj2)
}
https://go.dev/play/p/gUR5ed2n0D1
- 1 回答
- 0 关注
- 91 浏览
添加回答
举报
0/150
提交
取消