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

Jon Lara Source


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


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 = ""

    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 {

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


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