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

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

Unmarshal json into struct: cannot unmarshal array into Go value

问题

我有一个通过REST提供属性的服务。现在我想将响应体解组为一个属性结构体。请参考这个playground示例:点击。当我只有一个属性时,我可以轻松地将其解组为一个Property。然而,实际服务器返回的响应与之有所不同。我想要解组的实际响应如下:

  1. [
  2. {
  3. "key": "blabla",
  4. "secret": false,
  5. "type": "string",
  6. "value": "hereisthevalue"
  7. },
  8. {
  9. "key": "yepyepakey",
  10. "secret": true,
  11. "type": "string",
  12. "value": "dummy"
  13. }
  14. ]

不幸的是,我不知道如何解组这个响应。有人可以指点我正确的方向吗?

英文:

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:

  1. [
  2. {
  3. "key": "blabla",
  4. "secret": false,
  5. "type": "string",
  6. "value": "hereisthevalue"
  7. },
  8. {
  9. "key": "yepyepakey",
  10. "secret": true,
  11. "type": "string",
  12. "value": "dummy"
  13. }
  14. ]

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

  1. var props []Property
  2. er := json.Unmarshal(resp, &props)
  3. if er != nil {
  4. panic(er)
  5. } else {
  6. fmt.Println(props)
  7. }
英文:

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

  1. var props []Property
  2. er := json.Unmarshal(resp, &props)
  3. if er != nil {
  4. panic(er)
  5. } else {
  6. fmt.Println(props)
  7. }

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:

确定