【发布时间】:2021-11-11 14:29:47
【问题描述】:
我在从 URL 请求中读取 JSON 时遇到问题
我的 JSON
{"id" : "screens" ,"title" : "Skærmbilleder" ,"imagepath" : "https://www.spiritbooks.dk/service/menu/screens.png"},{"id" : "presale" ,"title" : "Presale" ,"imagepath" : "https://www.spiritbooks.dk/service/menu/presale.png"},{"id" : "discount" ,"title" : "Rabatkoder" ,"imagepath" : "https://www.spiritbooks.dk/service/menu/discount.png"},{"id" : "contact" ,"title" : "Kontakt" ,"imagepath" : "https://www.spiritbooks.dk/service/menu/contact.png"},{"id" : "about" ,"title" : "Om hjertechakra appen" ,"imagepath" : "https://www.spiritbooks.dk/service/menu/about.png"},
我的代码
AF.request("myUrl").responseJSON { response in
if let result = response.data {
do {
// make sure this JSON is in the format we expect
if let json = try JSONSerialization.jsonObject(with: result, options: []) as? [[String:Any]] {
for categoryData in json{
var category = Category()
if let id = categoryData["id"] as? String{
category.id = id
}
if let title = categoryData["title"] as? String{
category.title = title
}
if let imagepath = categoryData["imagepath"] as? String{
category.imagepath = imagepath
}
self.categories.append(category)
}
}
} catch let error as NSError {
print("Failed to load: \(error.localizedDescription)")
}
}
}
}
}
我收到错误代码“加载失败:无法读取数据,因为它的格式不正确”
【问题讨论】:
-
print("Failed to load: \(error.localizedDescription)")=>print("Failed to load: \(error) with response: \(String(data: result, encoding: .utf8))")并给我们输出 -
...并删除
let error as NSError
标签: ios json swift url alamofire