Swift - 解析多个选项Json答案

时间:2016-02-11 23:39:52

标签: json swift parsing optional

下面的代码工作正常,至少在我的几个测试中。问题是我真的不知道我是否覆盖了代码中的每一个可能的失败,或者这是处理倍数的最佳方法“if let ...”Optionals。有没有更好,更实际的方法来做到这一点?代码只是为了处理我从Youtube API获得的数据。

func requestPlaylistTrailers(){
        let playlist = self.playlistIdTrailers
        self.delegate?.youtubeTrailersWillUpdate()
        self.req(playlist) { (myData) -> Void in
            var title = ""
            var videoId = ""
            var thumbnail = ""
            if myData != nil{
                let data = myData!
                let items = data["items"] as! Array<AnyObject>
                for item in items {
                    //print(item)
                    if let itemDict = item as? Dictionary<NSObject,AnyObject>{
                        if let snippet  = itemDict["snippet"] as? Dictionary<NSObject,AnyObject> {
                            if let getTitle = snippet["title"] as? String{ title = getTitle}
                            if let getVideoId = snippet["resourceId"] as? Dictionary<NSObject,AnyObject> {
                                if let getVideoId2 = getVideoId["videoId"] as? String{ videoId = getVideoId2}
                            }
                            if let myThumb = snippet["thumbnails"] as? Dictionary<NSObject,AnyObject>{
                                if let myHighThumb = myThumb["high"] as? Dictionary<NSObject,AnyObject>{
                                    if let thumbUrl = myHighThumb["url"] as? String{
                                        thumbnail = thumbUrl
                                    }
                                }
                            }
                        }
                    }
                    if (thumbnail != "" && videoId != ""){
                        self.arrayYoutubeTrailers.append(["title": title,"videoId": videoId, "thumbnail": thumbnail])
                    }
                }
                self.delegate?.youtubeTrailersDidUpdate(self.arrayYoutubeTrailers)
            } else {
                self.delegate?.youtubeTrailersFailed()
            }
        }
    }

由于答案可以没有“缩略图”或“标题”,我已经得到了类似的答案,我必须检查所有内容或应用程序崩溃。

只是为了通知你,这是答案中的一个项目

{
    contentDetails =     {
        videoId = "va-0o_xBVnU";
    };
    etag = "\"DsOZ7qVJA4mxdTxZeNzis6uE6ck/spb02vX6UoYkYSIcBFTCzlPQ3Es\"";
    id = "PLegkaUUrMBQZ7KYS4cdBhF5aRmyOFe-zLBqlqoAM_wH4";
    kind = "youtube#playlistItem";
    snippet =     {
        channelId = UCi8e0iOVk1fEOogdfu4YgfA;
        channelTitle = "Movieclips Trailers";
        description = "Subscribe to TRAILERS: http://bit.ly/sxaw6h\nSubscribe to COMING SOON: http://bit.ly/H2vZUn\nLike us on FACEBOOK: http://goo.gl/dHs73\nFollow us on TWITTER: http://bit.ly/1ghOWmt \nMoney Monster Official Trailer #1 (2016) - George Clooney, Julia Roberts Movie HD\n\nIn the taut and tense thriller Money Monster, Lee Gates (George Clooney) is a bombastic TV personality whose popular financial network show has made him the money wiz of Wall Street. But after he hawks a high tech stock that mysteriously crashes, an irate investor (Jack O'Connell) takes Gates, his crew, and his ace producer Patty Fenn (Julia Roberts) hostage live on air. Unfolding in real time, Gates and Fenn must find a way to keep themselves alive while simultaneously uncovering the truth behind a tangle of big money lies.\n\n\nThe Fandango MOVIECLIPS Trailers channel is your destination for the hottest new trailers the second they drop. Whether it's the latest studio release, an indie horror flick, an evocative documentary, or that new RomCom you've been waiting for, the Fandango MOVIECLIPS team is here day and night to make sure all the best new movie trailers are here for you the moment they're released.\n\nIn addition to being the #1 Movie Trailers Channel on YouTube, we deliver amazing and engaging original videos each week. Watch our exclusive Ultimate Trailers, Showdowns, Instant Trailer Reviews, Monthly MashUps, Movie News, and so much more to keep you in the know.\n\nHere at Fandango MOVIECLIPS, we love movies as much as you!";
        playlistId = "PLScC8g4bqD47c-qHlsfhGH3j6Bg7jzFy-";
        position = 26;
        publishedAt = "2016-01-13T17:25:53.000Z";
        resourceId =         {
            kind = "youtube#video";
            videoId = "va-0o_xBVnU";
        };
        thumbnails =         {
            default =             {
                height = 90;
                url = "https://i.ytimg.com/vi/va-0o_xBVnU/default.jpg";
                width = 120;
            };
            high =             {
                height = 360;
                url = "https://i.ytimg.com/vi/va-0o_xBVnU/hqdefault.jpg";
                width = 480;
            };
            maxres =             {
                height = 720;
                url = "https://i.ytimg.com/vi/va-0o_xBVnU/maxresdefault.jpg";
                width = 1280;
            };
            medium =             {
                height = 180;
                url = "https://i.ytimg.com/vi/va-0o_xBVnU/mqdefault.jpg";
                width = 320;
            };
            standard =             {
                height = 480;
                url = "https://i.ytimg.com/vi/va-0o_xBVnU/sddefault.jpg";
                width = 640;
            };
        };
        title = "Money Monster Official Trailer #1 (2016) - George Clooney, Julia Roberts Movie HD";
    };
}

提前致谢。

1 个答案:

答案 0 :(得分:1)

您可以将“if let”代码链接在一起,这样至少它看起来不那么难看。然后而不是;

if let ...
    if let ...
        if let ... etc

你刚才

if let ...,
   let ...,
   let ... {
    // All good, do stuff
} else {
    // Something went wrong
}

然后你只需要处理其他一个条件。