我正在尝试从我自己的API检索数据,如果我尝试使用Chrome浏览器连接到我的API,它会像这样提供JSON数据
{" ID":" 52""用户名":" aasad23""全名":& #34; aasad laksana""电子邮件":" aasad@gmail.com","化身":" /应用/ XAMPP / xamppfiles / htdocs中/微/Avatar/52/avatar.jpg"}
但是,当我尝试通过我的iOS应用程序访问API时,它在执行JSON序列化时出错,它会出错: 无法读取数据,因为格式不正确
正确的格式是什么意思?
我已检查过此行中的代码错误
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
这就是为什么catch
错误被激活并给出错误消息。
这是此任务的完整代码
URLSession.shared.dataTask(with: request) { data, response, error in
DispatchQueue.main.async(execute: {
if error == nil {
do {
// json containes $returnArray from php
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
// declare new parseJSON to store json
guard let parsedJSON = json else {
print("Error while parsing")
return
}
print(parsedJSON)
// get id from $returnArray["id"] in PHP - parseJSON["id"]
let id = parsedJSON["id"]
// successfully uploaded
if id != nil {
// save user information yang berasal dari server
UserDefaults.standard.set(parsedJSON, forKey: "parsedJSON")
} else {
// get main queue to communicate back to user
DispatchQueue.main.async(execute: {
let message = parsedJSON["message"] as! String
self.showAlert(alertTitle: "opppps", alertMessage: message, actionTitle: "OK")
})
}
// JSON serialization error
} catch {
// get main queue to communicate back to user
DispatchQueue.main.async(execute: {
let message = error.localizedDescription
self.showAlert(alertTitle: "Sorry", alertMessage: message, actionTitle: "OK")
})
}
// error when connecting to server
} else {
// get main queue to communicate back to user
DispatchQueue.main.async(execute: {
let message = error!.localizedDescription
self.showAlert(alertTitle: "oppps", alertMessage: message, actionTitle: "OK")
})
}
})
}.resume()
}
答案 0 :(得分:1)
试
CoverP3D cover = new CoverP3D();
而不是
let json = try JSONSerialization.jsonObject(with: data, options: []) as! [String: AnyObject]