将JSON解析为具有”嵌入”键的结构体。

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

Unmarshal JSON as struct with "embedded" key

问题

我有这个JSON:

  1. {
  2. "id": "12345",
  3. "videos": {
  4. "results": [
  5. {
  6. "id": "533ec655c3a3685448000505",
  7. "key": "cYyx5DwWu0k"
  8. }
  9. ]
  10. }
  11. }

我想将其解组为以下结构:

  1. type Film struct {
  2. ID int `json:"id"`
  3. Videos []Video `json:"videos.results"`
  4. }
  5. type Video struct {
  6. ID string `json:"id"`
  7. Key string `json:"key"`
  8. }

我的意思是,我希望Videos结构字段是videos.results数组。

如果我这样做:

  1. body := //获取上面的JSON
  2. var film Film
  3. json.Unmarshal(body, &film)

显然不起作用,因为它无法将videos JSON键解组为Video数组,因为有results键。

我该如何做到这一点?

英文:

I have this JSON:

  1. {
  2. id : "12345",
  3. videos: {
  4. results: [
  5. {
  6. id: "533ec655c3a3685448000505",
  7. key: "cYyx5DwWu0k"
  8. }
  9. ]
  10. }
  11. }

And I want to unmarshal it to this struct:

  1. type Film struct {
  2. ID int `json:"id"`
  3. Videos []Video `json:"videos"`
  4. }
  5. type Video struct {
  6. ID string `json:"id"`
  7. Key string `json:"key"`
  8. }

I mean, I want to Videos struct field to be videos.results array.

If I do this:

  1. body := //retrieve json above
  2. var film Film
  3. json.Unmarshal(body, &film)

obviously doesn't work because it can't unmarshal videos json key to a Video array because of results key.

How can I do this?

答案1

得分: 2

你可以为Film定义一个解码器,它可以为你"解开"嵌套的JSON结构。示例代码如下:

  1. func (f *Film) UnmarshalJSON(b []byte) error {
  2. internal := struct {
  3. ID int `json:"id"`
  4. Videos struct {
  5. Results []Video `json:"results"`
  6. } `json:"videos"`
  7. }{}
  8. if err := json.Unmarshal(b, &internal); err != nil {
  9. return err
  10. }
  11. f.ID = internal.ID
  12. f.Videos = internal.Videos.Results
  13. return nil
  14. }

你可以在这里查看示例代码:https://play.golang.org/p/rEiKqLYB-1

英文:

You can define an unmarshaller for Film that "unpacks" the nested JSON structure for you. Example:

  1. func (f *Film) UnmarshalJSON(b []byte) error {
  2. internal := struct {
  3. ID int `json:"id"`
  4. Videos struct {
  5. Results []Video `json:"results"`
  6. } `json:"videos"`
  7. }{}
  8. if err := json.Unmarshal(b, &internal); err != nil {
  9. return err
  10. }
  11. f.ID = internal.ID
  12. f.Videos = internal.Videos.Results
  13. return nil
  14. }

https://play.golang.org/p/rEiKqLYB-1

huangapple
  • 本文由 发表于 2016年9月5日 01:00:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/39319380.html
匿名

发表评论

匿名网友

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

确定