"image_url": "\/a725405c-a26a-4974-bcb0-d7fdef766f99.png", "url": "\/products\/2d-apple-games-by-tutorials" } Swift struct Product { let name: String let image_url: URL? let url: URL? let sku: String }
AnyObject = json { if let array = json as? NSArray { for jsonItem in array as [AnyObject] { if let id = jsonItem.valueForKey("id") as? Int { if let name = jsonItem.valueForKey("name") as? String { if let url_string = jsonItem.valueForKey("url") as? String { if let fork = jsonItem.valueForKey("fork") as? Bool { if let url = NSURL(string: url_string) { let description = jsonItem.valueForKey("description") as? String var homepage: NSURL? = .None if let homepage_string = jsonItem.valueForKey("homepage") as? String { homepage = NSURL(string: homepage_string) } let repo = Repo(id: id, name: name, desc: description, url: url, homepage: homepage, fork: fork) repos += [repo] } } } } } } } } 1 This Swift is 2.5 years old
var repos = [Repo]() for (index: String, subJson: JSON) in json { if let id = subJson["id"].int, let name = subJson["name"].string, let url = subJson["url"].string, let fork = subJson["fork"].bool { var homepage: NSURL? = .None if let homepage_raw = subJson["homepage"].string { homepage = NSURL(string: homepage_raw) } let url_url = NSURL(string: url)! repos += [Repo(id: id, name: name, desc: subJson["description"].string, url: url_url, homepage: homepage, fork: fork)] } } 2 It's from a blog I wrote about different JSON parsing options in Swift.