简体   繁体   中英

How do I reference an object within an array within an object in xcode 8?

I'm looking to try and reference all "titles" within this json ( link here ) in xcode 8. The issue is there's an object and array that need to be referenced (i believe) before I can pull the title data, and I'm not sure how to do that.

So far this is what i've got:

func fetchFeed(){
    let urlRequest = URLRequest(url: URL(string: "http://itunes.apple.com/us/rss/topalbums/limit=10/json")!)

    let task = URLSession.shared.dataTask(with: urlRequest) { (data,response,error) in

        if error != nil {
            print(error)
            return
        }

        self.artists = [Artist]()
        do {
            let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! [String : AnyObject]

            if let feedFromJson = json["feed"]?["entry"] as? [[String : AnyObject]] {
                for feedFromJson in feedsFromJson {
                    let feed = Feed()
                    if let entry = feedFromJson["entry"] as? String, let author = feedFromJson["domain"] as? String {

                        feed.entry = entry

                        article.headline = title

                    }
                    self.articles?.append(article)
                }
            }
            DispatchQueue.main.async {
                self.tableview.reloadData()

And thank you for your help in advance!

  1. There is two kinds of titles. the "feed" and the "entry".

if let entry = feedFromJson["entry"] as? String, let author = feedFromJson["domain"] as? String {

The practice of iOS is not this.

is nil ,not a string . 为nil,不是字符串。 I guess you try to get the "feed" title.

if let entry = (json["feed"] as Dictionary)?["title"]

To get the "entry" title. Just traverse the array, and get the title.

let titleDict = feedFromJson["title"] as? Dictionary
let title = titleDict["title"] as? String
article.headline = title
  1. Better to know the structure of the JSON data.

It's too quick.

if let feedFromJson = json["feed"]?["entry"] as? [[String : AnyObject]] {

You should step by step.

if let feedFromJson = (json["feed"] as Dictionary)?["entry"] as? [[String : AnyObject]] {

I'm working hard to try to understand what you need. If you want to get an Article array where the headline is the title label for the entry, here is how I cheated it out.

func articles(from json: Any?) -> [Article] {
    guard let json = json as? NSDictionary, let entries = json.value(forKeyPath: "feed.entry") as? [NSDictionary] else {
        return []
    }

    return entries.flatMap { entry in
        guard let title = entry.value(forKeyPath: "title.label") as? String else {
            return nil
        }

        var article = Article()
        article.headline = title
        return article
    }
}

you call it as such

self.articles = articles(from: json)

NSDictionary has the method value(forKeyPath:) that is near magic. Calling json.value(forKeyPath: "feed.entry") returns an array of dictionaries. Each dictionary is an "entry" object in the json. Next, I map each entry to call entry.value(forKeyPath: "title.label") which returns a string.


If this is something more than a quick solution, then I would consider adding SwiftyJSON to your project.

func articles(from json: Any?) -> [Article] {
    return JSON(json)["feed"]["entry"].arrayValue.flatMap { entry in
        guard let title = entry["title"]["label"].string else {
            return nil
        }

        var article = Article()
        article.headline = title
        return article
    }
}

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