简体   繁体   中英

Golang json.Unmarshal is not working as expected

Im trying to unmarshal json response from vcenter rest api. when the response body is simply printed it looks like the o/p below

{"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}]}

i have exported both struct and struct fields however the fields like memory_size_MiB, power_state,cpu_count is not being unmarshalled. when the struct is printed it looks like below:-

{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}]}% 

Below is my 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
    }
    
    func main(){
    //authpart
    loginurl = "https://sandbox.vmware.local/rest/com/vmware/cis/session"
    //login...
    err = json.Unmarshal([]byte(string(body)),&sessVal)
    if  err != nil{
        log.Fatal(err)
    }
    var allvmlist ColVmList
    allvmlist = getVmList(sessVal.VmwareApiSessionId,&cli)
    fmt.Printf("%v",allvmlist)
    }

Your struct tags are not well formed. Remove the space between json: and the string "..." in the struct tags. ie it MUST be json:"..." not json: "..." .

And the reason some fields are correctly unmarshaled even with not well-formed struct tags is because the fields' names match the json property names.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM