我有一个代码来从php返回Json获取员工数据,如下所示:
[{"id":"1","email":"KK","password":"KKK","firstName":"KKK","lastName":"KK","photo":null,"phone":"22","mobile":"2","position":"SS","adminstrator_id":"1","department_id":"1"}]
代码我试过:
func getEmpById (id:String) {
emp = employee()
let myUrl = NSURL(string:"http://localhost/On%20Call%20App/scripts/getEmployee.php?id=\(id)")
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithURL(myUrl!, completionHandler: {
(data, response, error) -> Void in
do {
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as! [[String: AnyObject]]
let dic = json[0]
if let id = dic["id"] , firstName = dic["firstName"] ,lastName = dic["lastName"], mobile = dic["mobile"],phone = dic["phone"],email=dic["email"],pos=dic["position"]{
self.emp.setId(id as! String )
self.emp.setFirstName(firstName as! String)
self.emp.setLastName(lastName as! String)
self.emp.setPhone(phone as! String)
self.emp.setMobile(mobile as! String)
self.emp.setEmail(email as! String)
self.emp.setPosition(pos as! String)
}
} catch {
print(error)
}
})
task.resume()
}
此行let task = session.dataTaskWithURL(myUrl!, completionHandler:{
中的问题当应用到达此行时,它将直接转到task.resume()
而不会打印任何错误
有什么帮助使这项工作?
答案 0 :(得分:1)
您的回复属于Array
类型而不是Dictionary
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as! NSArray
let dic = json[0] as! NSDictionary
print(dic.objectForKey("email"))
如果使用像这样的Swift数组,那就好了。
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as! [[String: AnyObject]]
let dic = json[0]
print(dic["email"])