from this link I would like to get the commonName
I tried this but it didn't work?!
let commonName = object["toLocationDisambiguation"][0]["disambiguationOptions"][1]["place"][2]["commonName"].stringValue
from this link I would like to get the commonName
I tried this but it didn't work?!
let commonName = object["toLocationDisambiguation"][0]["disambiguationOptions"][1]["place"][2]["commonName"].stringValue
Option 1 (Normal)
if let toLocationDisambiguation = object["toLocationDisambiguation"] as? Dictionary<String, AnyObject> {
if let disambiguationOptions = toLocationDisambiguation["disambiguationOptions"] as? Array<AnyObject> {
if let first = disambiguationOptions.first as? [String: AnyObject] {
if let place = first["place"] as? [String: AnyObject] {
let commonName = place["commonName"] as! String
print("Common Name: ", commonName)
}
}
}
}
Option 2 (Type Aliases)
typealias MyDictionary = [String: AnyObject]
typealias MyArray = [MyDictionary]
if let toLocationDisambiguation = object["toLocationDisambiguation"] as? MyDictionary {
if let disambiguationOptions = toLocationDisambiguation["disambiguationOptions"] as? MyArray {
if let first = disambiguationOptions.first {
if let place = first["place"] as? MyDictionary {
let commonName = place["commonName"] as! String
print("Common Name: ", commonName)
}
}
}
}
Option 3 (SwiftyJSON for Objective-C like syntax)
Take a look at SwiftyJSON.
let object = try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as! Dictionary<String, AnyObject>
let json = JSON(object)
let commonName = json["toLocationDisambiguation"]["disambiguationOptions"][0]["place"]["commonName"].stringValue
print("Common Name: ", commonName)
if let disambiguations = object["toLocationDisambiguation"] as? MyArray { if let commonName = disambiguations.first as? MyDictionary { let commonName = object["commonName"].stringValue } } now I get the error: downcast form 'MyDictionay?' to 'MyDictionary'as? MyDictionary as it's unnecessary.for (_,object):(String, JSON) in readableJSON { typealias MyDictionary = [String: AnyObject] typealias MyArray = [MyDictionary] if let disambiguations = object["toLocationDisambiguation"] as? MyArray { if let first = disambiguations.first { let commonName = disambiguations NSLog("Dis: \(disambiguations)") } } commonNameArray.append(commonName) NumberOfRows = commonNameArray.countlet jsonData = NSData(contentsOfURL: url!) let readableJSON = JSON(data: jsonData!, options: NSJSONReadingOptions.MutableContainers, error: nil) let object = try! NSJSONSerialization.JSONObjectWithData(jsonData!, options: NSJSONReadingOptions.AllowFragments) as! Dictionary<String, AnyObject> let json = JSON(object) for (_,object):(String, JSON) in readableJSON { let commonName = json["toLocationDisambiguation"]["disambiguationOptions"][0]["place"]["commonName"].stringValue commonNameArray.append(commonName)