drpsrvu85668 2016-09-04 17:00
浏览 25
已采纳

使用“嵌入式”密钥将JSON解组为结构

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条回答 默认 最新

  • doujing6053 2016-09-04 17:06
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用