JSON:从DB读取数组

时间:2015-06-04 14:11:22

标签: json database swift xcode6

我需要从数据库中获取位置,它是一个数组。

我已经尝试了很多代码,但是每个代码都会给我一个错误,例如“无法将NSArray类型的值转换为NSDictionary”或类似的东西。

这是我的最后一次尝试:

let jsonData:NSDictionary = NSJSONSerialization.JSONObjectWithData(urlData!, options:NSJSONReadingOptions.MutableContainers , error: &error) as! NSDictionary
var location = ((jsonData as NSDictionary)["locations"] as! NSDictionary)["location_name"] as! String
println(customernamedb)

这是我的回答:

  

{ “状态”: “1”, “CITY_NAME”: “孟买”, “city_id”: “3”, “位置”:[{ “LOCATION_ID”: “1”, “LOCATION_NAME”: “安泰”} ,{“location_id”:“2”,“location_name”:“Lower Parel”},{“location_id”:“59”,“location_name”:“Lower Parel”},{“location_id”:“102”,“location_name “:”Lower Parel“},{”location_id“:”144“,”location_name“:”Borivali“},{”location_id“:”145“,”location_name“:”Borivali“},{”location_id“:” 146" , “LOCATION_NAME”: “包里瓦利”},{ “LOCATION_ID”: “147”, “LOCATION_NAME”: “安泰”}]}

我需要阅读所有location_name

1 个答案:

答案 0 :(得分:2)

您正在尝试访问数组,就像它是字典一样......

注意:您应该分解语句并使用安全解包,而不是将所有内容堆叠在同一行上。

示例:

if let jsonData = NSJSONSerialization.JSONObjectWithData(urlData!, options: nil, error: &error) as? [String:AnyObject] { // dictionary
    if let locationsArray = jsonData["locations"] as? [[String:AnyObject]] { // array of dictionaries
        for locationDictionary in locationsArray { // we loop in the array of dictionaries
            if let location = locationDictionary["location_name"] as? String { // finally, access the dictionary like you were trying to do
                println(location)
            }
        }
    }
}

Swift 2.0更新

do {
    if let jsonData = try NSJSONSerialization.JSONObjectWithData(urlData!, options: []) as? [String:AnyObject] {
        if let locationsArray = jsonData["locations"] as? [[String:AnyObject]] {
            for locationDictionary in locationsArray {
                if let location = locationDictionary["location_name"] as? String {
                    print(location)
                }
            }
        }
    }
} catch {
    print(error)
}