将json解组为结构体:不能将数组解析为Go值 [英] Unmarshal json into struct: cannot unmarshal array into Go value
问题描述
我有一项通过REST为我提供属性的服务。现在我想将身体解组到一个属性结构中。请参阅此操场示例:点击。当我只有一个属性时,我可以轻松将它解组为 Property
。然而,来自服务器的ACTUAL响应在某种程度上是不同的。我想解组的实际响应是这样的:
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?
推荐答案
您需要解组成一片属性:
< a href =http://play.golang.org/p/eRgjfBHypH> http://play.golang.org/p/eRgjfBHypH
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)
}
这篇关于将json解组为结构体:不能将数组解析为Go值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!