我在解析json时试图从本地服务器获取一些数据。在视图控制器中,我访问本地Ruby on Rails服务器:
override func viewDidLoad() {
super.viewDidLoad()
var url = NSURL(scheme: "http", host: "0.0.0.0:3000", path: "/api/search?query=auto")
var request = NSURLRequest(URL: url)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {(data, response, error) in
var data1: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
println(data1)
println(data1["companies"])
var companies = data1["companies"] as NSArray
for company: AnyObject in companies {
println(company)
}
}
task.resume()
}
println(data1)
返回:
{
companies = "[{\"alias\":\"02-avtomoyka-tulybaev-r-t\",\"id\":45693},{\"alias\":\"1001-zapchast-internetmagazin-avtotovarov\",\"id\":42621}]";
}
使用println(data1["companies"])
,我在控制台中获得了一系列对象:
[{"alias":"02-avtomoyka-tulybaev-r-t","id":45693},{"alias":"1001-zapchast-internetmagazin-avtotovarov","id":42621}]
然后,当我试图遍历该数组时,应用程序崩溃了。我究竟做错了什么?
它在控制台中没有任何错误,但在Tread 6中(lldb)
和EXC_BREAKPOINT(code=EXC_I386_BPT, subcode 0x0)
PS:Xcode也会在Constant 'company' inferred to have type 'AnyObject', which may be unexpected
字符串处抛出编译器问题for company in companies {
。我怎么处理呢?
答案 0 :(得分:1)
而不是var companies = data1["companies"] as NSArray
尝试var companies = data1["companies"].allValues;
问题是data1["companies"]
是字典,无法隐式转换为NSArray
。编译器没有抓住这个,因为data1["companies"]
作为NSDictionary
存储在AnyObject
中,并允许您将其强制转换为任何子类。