Swift JSON 未解析数据 Swift

Swift JSON not parsing Data Swift

我正在尝试将 YouTube 数据 API 中的数据解析为 swift 字符串。因此,我正在使用 Alamofire 以及 SwiftyJSON。但是,SwiftyJSON 不解析任何内容,我得到一个错误 "Unexpectedly found nil while unwrapping an Optional value".

我的API通话

YTDataService.fetchDetails(forVideo: videoId, parts: [VideoPart.statistics, VideoPart.contentDetails], onDone: {(details) in
                    // details is of Type JSON
                    let videoDuration = details["items"]["contentDetails"]["duration"].string! // not parsing
                    let videoViews = details["items"]["statistics"]["viewCount"].string! // not parsing

                    print(videoDuration, videoViews)
                })
            })

来自 YouTube 的 JSON 回应

{
 "kind": "youtube#videoListResponse",
 "etag": "\"8jEFfXBrqiSrcF6Ee7MQuz8XuAM/UwkUogFGo4AZoBzZtd5t6Tj8wk0\"",
 "pageInfo": {
  "totalResults": 1,
  "resultsPerPage": 1
 },
 "items": [
  {
   "kind": "youtube#video",
   "etag": "\"8jEFfXBrqiSrcF6Ee7MQuz8XuAM/qsX1KSuT5vhpp29lsFl_1l6uvWE\"",
   "id": "Dkk9gvTmCXY",
   "contentDetails": {
    "duration": "PT3M31S",
    "dimension": "2d",
    "definition": "hd",
    "caption": "true",
    "licensedContent": true,
    "projection": "rectangular"
   },
   "statistics": {
    "viewCount": "129895203",
    "likeCount": "3178074",
    "dislikeCount": "266720",
    "favoriteCount": "0",
    "commentCount": "230345"
   }
  }
 ]
}

如您所见,我尝试正确地解析数据 - 但出于某种原因,SwiftyJSON 没有正确解析数据。

如有任何帮助,我们将不胜感激!

您需要将items作为数组处理

if let item = details["items"].array.first , let dur = item["contentDetails"]["duration"].string {
   print(dur)
}

viewCount

相同
if let item = details["items"].array.first , let videoCount = item["statistics"]["viewCount"].string {
   print(videoCount)
}

itemsarray 而不是 dictionary。您无法直接从中获取 contentDetails

items array 中获取 first 元素,然后从中获取 contentDetailsstatistics。然后进一步得到durationviewCount

YTDataService.fetchDetails(forVideo: videoId, parts: [VideoPart.statistics, VideoPart.contentDetails], onDone: {(details) in
    if let item = details["items"].array.first {
        let videoDuration = item["contentDetails"]["duration"].string
        let videoViews = item["statistics"]["viewCount"].string
        print(videoDuration, videoViews)
    }
})

videoDurationvideoViews 将被提取为 optionals。使用 if-letnil-coalescing (??) 运算符解包值。

您不能直接从数组中获取值,因此首先从数组中获取第一项,然后像下面的代码一样从此项中逐个获取值

guard let item = details["items"].array.first else { return }
let videoDuration = item["statistics"]["viewCount"].stringValue
let videoViews = item["statistics"]["viewCount"].stringValue