将JSON解组为结构体:无法将数组解组为Go值

huangapple go评论84阅读模式
英文:

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)
}

huangapple
  • 本文由 发表于 2015年12月11日 22:19:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/34225656.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定