英文:
Unmarshal json into struct: cannot unmarshal array into Go value
问题
我有一个通过REST提供属性的服务。现在我想将响应体解组为一个属性结构体。请参考这个playground示例:点击。当我只有一个属性时,我可以轻松地将其解组为一个Property
。然而,实际服务器返回的响应与之有所不同。我想要解组的实际响应如下:
[
{
"key": "blabla",
"secret": false,
"type": "string",
"value": "hereisthevalue"
},
{
"key": "yepyepakey",
"secret": true,
"type": "string",
"value": "dummy"
}
]
不幸的是,我不知道如何解组这个响应。有人可以指点我正确的方向吗?
英文:
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
得分: 19
你需要将其解组为 Property 的切片:
http://play.golang.org/p/eRgjfBHypH
var props []Property
er := json.Unmarshal(resp, &props)
if er != nil {
panic(er)
} else {
fmt.Println(props)
}
英文:
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)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论