簡體   English   中英

無法解碼 JSON:無法讀取數據,因為它的格式不正確

[英]Could not decode JSON: The data couldn’t be read because it isn’t in the correct format

更新

我收到錯誤消息“錯誤!無法解碼 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()

1 - 您應該在加載完成時緩存數據,以便在您再次滾動到此單元格時不重新加載
2 - 您可以在加載單元格 0 -> 10 -> 的數據時顯示加載全屏,並在完成所有操作后重新加載 tableview
3 - 您可以從服務器更新以在 1 個請求中加載多個項目,而不是在應用程序中進行更新
希望對你有用

這個問題不再與標題有關。

反正。 您的 JSON 不是 TodoItem 數組。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM