简体   繁体   中英

How can I get data from JSON array in SWIFT?

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)

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