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

Jon Lara Source

UPDATE

I get the error "Error! Could not decode JSON: The data couldn’t be read because it isn’t in the correct format.". The JSON from the request is

{"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}]}

Why is it not working? I don't know how to get the answer...

My code and structure:

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

Answers

answered 1 month ago Nguyen Hoan #1

1 - You should cache data when the load finish to not reload when you scroll to this cell again
2 - You can show loading fullscreen when you load data of cell 0 -> 10 -> and reload tableview when finish all of them
3 - Instead of an update in the app, you can update from server to load many items in just 1 request
Hope useful for you

answered 1 month ago Aleksandr Konakov #2

The question has nothing to do with the title anymore.

Anyway. Your JSON is not an array of TodoItem.

comments powered by Disqus