Unmarshal json into struct: cannot unmarshal array into Go value

你说的曾经没有我的故事 提交于 2019-12-23 09:59:23

问题


I have a service which provides me properties through REST. Now I want to unmarshal the body into a properties struct. Please see this playground example: click. When I have only one property, I can easily unmarshal it into a Property. However the ACTUAL response from the server is somehow difference. The actual response I want to unmarshal is this:

[
    {
        "key": "blabla",
        "secret": false,
        "type": "string",
        "value": "hereisthevalue"
    },
    {
        "key": "yepyepakey",
        "secret": true,
        "type": "string",
        "value": "dummy"
    }
]

Unfortunately I don't know how to unmarshal this. Can someone please point me in the right direction?


回答1:


You need to unmarshal into a slice of Property: http://play.golang.org/p/eRgjfBHypH

var props []Property
er := json.Unmarshal(resp, &props)
if er != nil {
    panic(er)
} else {
    fmt.Println(props)
}


来源:https://stackoverflow.com/questions/34225656/unmarshal-json-into-struct-cannot-unmarshal-array-into-go-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!