【问题标题】:The data couldn't be read because it isn't in the correct format - swift无法读取数据,因为它的格式不正确 - swift
【发布时间】: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


【解决方案1】:

您的 JSON 不合法。将其粘贴到jsonlint 中,它会向您显示错误。您的数据似乎是一个 JSON 数组,但它没有包含在 [...] 中。

【讨论】:

    猜你喜欢
    • 2019-07-28
    • 1970-01-01
    • 1970-01-01
    • 2017-06-12
    • 2018-12-25
    • 2020-03-11
    • 1970-01-01
    • 2016-10-15
    相关资源
    最近更新 更多