简体   繁体   中英

Accessing JSON Objects parsed from iTunes API in Swift 3.0

I am trying to access items parsed in JSON from the iTunes API using Swift 3.0, but I am struggling to access the objects after they have been parsed. The objects are being parsed in this format:

{
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;
    },

I want to be able to access the information from all 50 results, such as the artistName, for instance. This is my parsing function attempting to get the artistName and add it to my NSDictionary, but it keeps returning that it can't unwrap the dictionary.

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

It looks like results is an array of dictionaries, not just a dictionary.

Instead of this: if let results = json["results"] as? NSDictionary if let results = json["results"] as? NSDictionary

try this: if let results = json["results"] as? NSArray if let results = json["results"] as? NSArray

You could then map or iterate over each element in the array, extracting "artistName" from each one, for example.

results is an array of dictionaries, not a dictionary itself. Try changing this:

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

to:

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

and then iterating over results. Each element of results is a dictionary with attributes such as artistName .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM