首页 > 解决方案 > 无法解码 JSON:无法读取数据,因为它的格式不正确

问题描述

更新

我收到错误“错误!无法解码 JSON:无法读取数据,因为它的格式不正确。”。请求中的 JSON 是

{"page":0,"pageSize":100,"totalPages":1,"numberOfElements":1,"totalElements":1,"hasPreviousPage":false,"hasNextPage":false,"content":[{"id":4554053904,"externalAccountId":null,"source":"PLAN","amount":1073741824,"reportId":null,"rowId":null,"timeCharged":1533427200000,"timeCreated":1533476043000}]}

为什么它不起作用?我不知道如何得到答案...

我的代码和结构:

struct TodoItem: Decodable {
    let page: Int?
    let pageSize: Int?
    let totalPages: Int?
    let numberOfElements: Int?
    let totalElements: Int?
    let hasPreviousPage: Bool
    let hasNextPage: Bool
    let content: [content]



}

struct content: Decodable {
    let id: Int?
    let externalAccountId: String?
    let source: String?
    let amount: Int?
    let reportId: Int?
    let rowId: Int?
    let timeCharged: Int?
    let timeCreated: Int?
}
func decodeJson() {


   let jsonUrlString = "myurl.com"
    print(jsonUrlString)




    guard let url = URL(string: jsonUrlString) else { return }
    URLSession.shared.dataTask(with: url) { (mydata, response, error2) in
        guard let datos = mydata else { return }

        do {
            self.todoList = try JSONDecoder().decode([TodoItem].self, from: datos)
            DispatchQueue.main.async {
                self.tableView.reloadData()
            }





        } catch let jsonError {
            print("Error! Could not decode JSON: \(jsonError.localizedDescription)")
        }
    }.resume()

标签: iosuitableviewnsurlsessiondatatask

解决方案


1 - 当您再次滚动到此单元格时,您应该在加载完成时缓存数据而不重新加载
2 - 您可以在加载单元格 0 -> 10 -> 的数据时显示加载全屏,并在完成所有这些时重新加载 tableview
3 - 相反在应用程序的更新中,您可以从服务器更新以在 1 个请求中加载许多项目
希望对您有用


推荐阅读