简体   繁体   中英

Accessing *remote* JSON deeply nested objects in Swift

Remote JSON parsing in Swift is new for me and I've spent weeks trying to figure this one out.

The JSON I'm pulling from is this guy: http://www.odysseynewsmagazine.net/wp-json/wp/v2/posts?_embed

I'm trying to get to that "source_url" for an image for each post but it's nested within "media_details" which is nested within "wp:featuredmedia" which is nested within "_embedded" and I just keep getting errors.

The code I've written looks like this:

    func parseData() {
        fetchedSlug = []
        //from odyssey site
        let url = "http://www.odysseynewsmagazine.net/wp-json/wp/v2/posts?_embed"
        var request = URLRequest(url: URL(string: url)!)
        request.httpMethod = "GET"

        let configuration = URLSessionConfiguration.default
        let session = URLSession(configuration: configuration, delegate: nil, delegateQueue: OperationQueue.main)

        let task = session.dataTask(with: request) { (data, response, error) in
            if error != nil {
                print("Error")
            }
            else {
                do {
                    let fetchedData = try JSONSerialization.jsonObject(with: data!, options: .mutableLeaves) as! NSArray

                    //Json objects to variables
                    for eachFetchedSlug in fetchedData {
                        let eachSlug = eachFetchedSlug as! [String: Any]
                        let slug = eachSlug["slug"] as! String
                        let link = eachSlug["link"] as! String
                        self.fetchedSlug.append(Slug(slug: slug, link: link))
                    }
                    self.slugTableView.reloadData()
                }
                catch {
                    print("Error2")
                }
            }
        }
        task.resume()
    }
}//end of VC Class

class Slug {
    //define variables
    let slug: String?
    let link: String?

    init(slug: String?, link: String?) {
        self.slug = slug
        self.link = link
    }

    //creating dictionaries from Json objects
    init(slugDictionary: [String : Any]) {
        self.slug = slugDictionary["slug"] as? String
        link = slugDictionary["link"] as? String
    }
}

I'm also going to need the title of each post which is found in "rendered" within "title".

All of this info is populating labels within a reusable custom cell within a tableView. I can populate the slug and link labels, but not any of the nested info.

What's up with the underscore preceding "embedded"? Is that why I can't get to anything? Can I make it go away? I'm not allowed to download plugins or run custom scripts until I show them a working app.

install Better REST API Featured Images plugin

屏幕截图

Please check below code :

for eachFetchedSlug in fetchedData {
    let eachSlug = eachFetchedSlug as! [String: Any]
    let slug = eachSlug["slug"] as! String
    let link = eachSlug["link"] as! String
    self.fetchedSlug.append(Slug(slug: slug, link: link))

    let title = eachSlug["title"] as! [String: Any]
    let rendered = String(describing: title["rendered"])
    print(rendered) // this is title

    let embedded = eachSlug["_embedded"] as! [String: Any]
    let wpfeaturedmedias = embedded["wp:featuredmedia"] as! [Any]
    for wpfeaturedmedia in wpfeaturedmedias {
        let featuredmedia = wpfeaturedmedia as! [String: Any]
        let mediaDetails = featuredmedia["media_details"] as! [String: Any]
        let mediaDetailsSize = mediaDetails["sizes"] as! [String: Any]
        let mediaDetailsSizeThumbnail = mediaDetailsSize["thumbnail"] as! [String: Any] // getting only thumbnail. Based on you requirement change this to
        let image = String(describing: mediaDetailsSizeThumbnail["source_url"])
        print(image) // this is image
    }
}

I added the code for only retrieving thumbnail . In the sizes so many types( medium , medium_large ...) are there. Based on your requirement, change the value.

Its better to add if let check for optionals. Because so many conversions are there. If it fails in any conversion, it will crash.

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