在iOS中执行JSON序列化时失败,但通过浏览器访问API时确定无误
我试图从我自己的API中检索数据,如果我尝试使用Chrome浏览器连接到我的API,它会返回JSON数据这样在iOS中执行JSON序列化时失败,但通过浏览器访问API时确定无误
{"id":"52","username":"aasad23","fullname":"aasad laksana","email":"[email protected]","avatar":"/Applications/XAMPP/xamppfiles/htdocs/Twitter/Avatar/52/avatar.jpg"}
,但是,当我试图通过我的iOS应用程序来访问API,它提供了一个错误,而这样做JSON序列化,它给出一个错误: 数据无法读取,因为它不是” t格式正确
这是什么意思是正确的格式?
我已签,在这条线
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()
}
回答:
尝试
let json = try JSONSerialization.jsonObject(with: data, options: []) as! [String: AnyObject]
而不是
try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
以上是 在iOS中执行JSON序列化时失败,但通过浏览器访问API时确定无误 的全部内容, 来源链接: utcz.com/qa/262057.html