访问从Swift 3.0中的iTunes API解析的JSON对象

时间:2016-10-20 23:38:23

标签: ios json swift parsing

我正在尝试使用Swift 3.0从iTunes API访问JSON中解析的项目,但是在解析后我很难访问这些对象。正在以这种格式解析对象:

{
resultCount = 50;
results =     (
            {
        artistId = 70936;
        artistName = "Johnny Cash";
        artistViewUrl = "https://itunes.apple.com/us/artist/johnny-cash/id70936?uo=4";
        artworkUrl100 = "http://is2.mzstatic.com/image/thumb/Music3/v4/13/ae/73/13ae735e-33d0-1480-f51b-4150d4a45696/source/100x100bb.jpg";
        artworkUrl30 = "http://is2.mzstatic.com/image/thumb/Music3/v4/13/ae/73/13ae735e-33d0-1480-f51b-4150d4a45696/source/30x30bb.jpg";
        artworkUrl60 = "http://is2.mzstatic.com/image/thumb/Music3/v4/13/ae/73/13ae735e-33d0-1480-f51b-4150d4a45696/source/60x60bb.jpg";
        collectionCensoredName = "The Essential Johnny Cash";
        collectionExplicitness = notExplicit;
        collectionId = 251001680;
        collectionName = "The Essential Johnny Cash";
        collectionPrice = "14.99";
        collectionViewUrl = "https://itunes.apple.com/us/album/ring-of-fire/id251001680?i=251002253&uo=4";
        country = USA;
        currency = USD;
        discCount = 2;
        discNumber = 1;
        isStreamable = 1;
        kind = song;
        previewUrl = "http://a1144.phobos.apple.com/us/r1000/070/Music/b3/99/be/mzi.qvkhtgfg.aac.p.m4a";
        primaryGenreName = Country;
        releaseDate = "2002-02-12T08:00:00Z";
        trackCensoredName = "Ring of Fire";
        trackCount = 18;
        trackExplicitness = notExplicit;
        trackId = 251002253;
        trackName = "Ring of Fire";
        trackNumber = 15;
        trackPrice = "1.29";
        trackTimeMillis = 155707;
        trackViewUrl = "https://itunes.apple.com/us/album/ring-of-fire/id251001680?i=251002253&uo=4";
        wrapperType = track;
    },

我希望能够访问所有50个结果中的信息,例如artistName。这是我的解析函数,试图获取artistName并将其添加到我的NSDictionary中,但它不断返回它无法打开字典。

func parser() {
    let enteredText:String = (tbxSearch.text?.replacingOccurrences(of: " ", with: "+"))!
    let url = "https://itunes.apple.com/search?term=\(enteredText)"
    print(url)
    guard let urlRequest = URL(string: url) else
    {
        print("Error creating endpoint")
        return
    }
    let request = URLRequest(url: urlRequest)
    URLSession.shared.dataTask(with: request) {(data,response,error) in
        do
        {
            guard let data = data else
            {
                return
            }
            guard let json = try JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary else
            {
                return
            }
            if let results = json["results"] as? NSDictionary
            {
                self.avObjects.avDict.setValue("Artist Name", forKey: results["artistName"] as! String)
                print(self.avObjects.avDict)
            }
            else  
            {  
                print("Couldn't unwrap the dictionary.")
            }
            print(json)
        }
        catch let error as NSError
        {
            print(error.debugDescription)
        }
    }.resume()
}

2 个答案:

答案 0 :(得分:0)

看起来results是一个字典数组,而不仅仅是字典。

而不是:if let results = json["results"] as? NSDictionary

试试这个:if let results = json["results"] as? NSArray

然后,您可以映射或迭代数组中的每个元素,例如从每个元素中提取"artistName"

答案 1 :(得分:0)

results是一个字典数组,而不是字典本身。尝试更改此内容:

if let results = json["results"] as? NSDictionary

到:

if let results = json["results"] as? NSArray

然后迭代结果。结果的每个元素都是一个包含artistName

等属性的字典