Swift JSON not parsing Data Swift



我正在尝试将YouTube Data API中的数据解析快速字符串。因此,我正在使用Alamofire以及SwiftyJSON。但是,SwiftyJSON 不会解析任何内容,并且我收到错误"解包可选值时意外发现 nil"。

我的接口调用

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)
}

你不能直接从数组中获取值,所以首先从数组中获取第一项,然后像波纹管代码一样从这个项目中逐个获取值

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

items是一个array而不是一个dictionary。您无法直接从中获取contentDetails

itemsarray获取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-mergeesing(??( 运算符解开值的包装。

最新更新