英文:
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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论