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

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

Unmarshal JSON as struct with "embedded" key

问题

我有这个JSON:

{
  "id": "12345",
  "videos": {
    "results": [
      {
        "id": "533ec655c3a3685448000505",
        "key": "cYyx5DwWu0k"
      }
    ]
  }
}

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

type Film struct {
	ID     int     `json:"id"`
	Videos []Video `json:"videos.results"`
}

type Video struct {
	ID  string `json:"id"`
	Key string `json:"key"`
}

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

如果我这样做:

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

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

我该如何做到这一点?

英文:

I have this JSON:

{
  id : "12345",
  videos: {
    results: [
      {
        id: "533ec655c3a3685448000505",
        key: "cYyx5DwWu0k"
      }
    ]
  }
}

And I want to unmarshal it to this struct:

type Film struct {
	ID          int     `json:"id"`
	Videos      []Video `json:"videos"`
}

type Video struct {
	ID   string  `json:"id"`
	Key  string  `json:"key"`
}

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

If I do this:

body := //retrieve json above
var film Film
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结构。示例代码如下:

func (f *Film) UnmarshalJSON(b []byte) error {
    internal := struct {
        ID     int `json:"id"`
        Videos struct {
            Results []Video `json:"results"`
        } `json:"videos"`
    }{}

    if err := json.Unmarshal(b, &internal); err != nil {
        return err
    }
    f.ID = internal.ID
    f.Videos = internal.Videos.Results
    return nil
}

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

英文:

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

func (f *Film) UnmarshalJSON(b []byte) error {
	internal := struct {
		ID     int `json:"id"`
		Videos struct {
			Results []Video `json:"results"`
		} `json:"videos"`
	}{}

	if err := json.Unmarshal(b, &internal); err != nil {
		return err
	}
	f.ID = internal.ID
	f.Videos = internal.Videos.Results
	return nil
}

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:

确定