dqby43944 2016-07-17 11:56
浏览 94

将具有嵌套数组和对象的JSON数据解组到Go结构中

I am unmarshalling Youtube json response into Go struct by using the data received from Youtube API as follows:-

{
 "kind": "youtube#searchListResponse",
 "etag": "\"5g01s4-wS2b4VpScndqCYc5Y-8k/5xHRkUxevhiDF1huCnKw2ybduyo\"",
 "nextPageToken": "CBQQAA",
 "regionCode": "TH",
 "pageInfo": {
  "totalResults": 36,
  "resultsPerPage": 20
 },
 "items": [
  {
   "kind": "youtube#searchResult",
   "etag": "\"5g01s4-wS2b4VpScndqCYc5Y-8k/aMbszoNudZchce3BIjZC_YemugE\"",
   "id": {
    "kind": "youtube#video",
    "videoId": "fvh6CQ7FxZE"
   },
   "snippet": {
    "publishedAt": "2016-07-16T14:42:36.000Z",
    "channelId": "UCuX4iswo8acMxDNcbrceRYQ",
    "title": "Japan อร่อยสุดๆ:การประชันของ 2 สาวกับราเมงดังจากโอซาก้า#ramen",
    "description": "Ramen Kio ราเมนชื่อดังของโอซาก้าอัดแน่นด้วยเนื้อหมูชาชูแบบเต็มๆเส้นเหนีย...",
    "thumbnails": {
     "default": {
      "url": "https://i.ytimg.com/vi/fvh6CQ7FxZE/default.jpg",
      "width": 120,
      "height": 90
     },
     "medium": {
      "url": "https://i.ytimg.com/vi/fvh6CQ7FxZE/mqdefault.jpg",
      "width": 320,
      "height": 180
     },
     "high": {
      "url": "https://i.ytimg.com/vi/fvh6CQ7FxZE/hqdefault.jpg",
      "width": 480,
      "height": 360
     }
    },
    "channelTitle": "Japan aroi sudsud TV",
    "liveBroadcastContent": "none"
   }
  }
 ]
}

To do so, I have created a struct for this in Go

type YoutubeData struct {
    Kind          string `json:"kind"`
    Etag          string `json:"etag"`
    NextPageToken string `json:"nextPageToken"`
    RegionCode    string `json:"regionCode"`
    PageInfo      struct {
        TotalResults   string `json:"totalResults"`
        ResultsPerPage string `json:"resultsPerPage"`
    } `json:"pageInfo"`
    Items []struct {
        Kind string `json:"kind"`
        Etag string `json:"etag"`
        Id   struct {
            Kind    string `json:"kind"`
            VideoId string `json:"videoId"`
        } `json:"id"`
        Snippet struct {
            PublishedAt string `json:"publishedAt"`
            ChannelId   string `json:"channelId"`
            Title       string `json:"title"`
            Description string `json:"description"`
            Thumbnails  struct {
                Default struct {
                    Url    string `json:"url"`
                    Width  string `json:"width"`
                    Height string `json:"height"`
                } `json:"default"`
                Medium struct {
                    Url    string `json:"url"`
                    Width  string `json:"width"`
                    Height string `json:"height"`
                } `json:"medium"`
                High struct {
                    Url    string `json:"url"`
                    Width  string `json:"width"`
                    Height string `json:"height"`
                } `json:"high"`
            } `json:"thumbnails"`
            ChannelTitle         string `json:"channelTitle"`
            LiveBroadcastContent string `json:"liveBroadcastContent"`
        } `json:"snippet"`
    } `json:"items"`
}

I unmarshaled it by using this method

youtubeData := YoutubeData{}

if json.Unmarshal(b, &youtubeData); err != nil {

} else {

} 

In which b is the byte data received from Youtube API. I successfully got all data in the byte object as I printed it out to my console, however, once I unmarshaled it and tried to output it on the template by using {{.}}, I received

{youtube#searchListResponse "5g01s4-wS2b4VpScndqCYc5Y-8k/JwGY0TWwWswjZ9LOvemaF5yxsMo" CBQQAA TH { } []}

All data are unmarshaled except for the data in json object and array which are pageInfo and items. There are simply blank. I believe I exported them all correctly. Are there some additional steps to get the data into slice or struct nested inside another struct in Go when it comes to json unmarshalling?

  • 写回答

3条回答 默认 最新

  • doutang6600 2016-07-17 12:13
    关注

    Note that the json data contains numbers for TotalResults and ResultsPerPage. You can try decoding these as follows:

    PageInfo      struct {
        TotalResults   json.Number `json:"totalResults"`
        ResultsPerPage json.Number `json:"resultsPerPage"`
    } `json:"pageInfo"`
    

    Once you have the unmarshalled struct, you can get the number as:

    totalResults, _ := youtubeData.PageInfo.TotalResults.Int64()
    
    评论

报告相同问题?

悬赏问题

  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答