gpt4 book ai didi

php - 在 iOS 中进行 JSON 序列化时失败,但通过浏览器访问时 API 正常

转载 作者:行者123 更新时间:2023-11-29 11:38:27 25 4
gpt4 key购买 nike

我正在尝试从我自己的 API 检索数据,如果我尝试使用 chrome 浏览器连接到我的 API,它会像这样返回 JSON 数据

{"id":"52","username":"aasad23","fullname":"aasad laksana","email":"aasad@gmail.com","avatar":"/Applications/XAMPP/xamppfiles/htdocs/Twitter/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()


}

最佳答案

尝试

let json = try JSONSerialization.jsonObject(with: data, options: []) as! [String: AnyObject]

而不是

try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary

关于php - 在 iOS 中进行 JSON 序列化时失败,但通过浏览器访问时 API 正常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47865301/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com