-2

Hello everyone I always get the following error and I do not know how to fix it.

typeMismatch(Swift.Array, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode Array but found a dictionary instead.", underlyingError: nil))

In the Swift Class DataLoader.swift I make the URL request and I want to parse the json file into a Objekt from the Struct TaskData.swift. Then I Save this Objects into a List userData.

I want to show specific values of this objects in a table view.

But I became the Swift Decoding Error when I make this try decoder.decode([TaskData].self, from: data)

What I am doing wrong and how can I make it work?

{
  "result": [
    {
      "complexity": 3, 
      "deadline": "2020-12-10", 
      "description": "This is Task 1", 
      "priority": "A", 
      "state": "In Progress", 
      "title": "Task 1"
    }, 
    {
      "complexity": 3, 
      "deadline": "2020-12-10", 
      "description": "This is Task 2", 
      "priority": "A", 
      "state": "In Progress", 
      "title": "Task 2"
    }, 
    {
      "complexity": 3, 
      "deadline": "2020-12-10", 
      "description": "This is Task 3", 
      "priority": "A", 
      "state": "In Progress", 
      "title": "Task 3"
    }, 
    {
      "complexity": 3, 
      "deadline": "2020-12-10", 
      "description": "This is Task 4", 
      "priority": "A", 
      "state": "In Progress", 
      "title": "Task 4"
    }
  ]
}

import Foundation

struct TaskData: Codable {
    
    let complexity: String
    let deadline: String
    let description: String
    let priority: String
    let state: String
    let title: String
    
    init(title: String?, state: String?, priority: String?, description: String?,
         deadline: String?, complexity: String?) {
        self.title = title ?? ""
        self.state = state ?? ""
        self.priority = priority ?? ""
        self.description = description ?? ""
        self.deadline = deadline ?? ""
        self.complexity = complexity ?? ""
    }
}

import Foundation

public class DataLoader {
    
    @Published var userData = [TaskData]()
    
    init() {
        load()
        
    }

    func load() {
        
        // Create URL

        let url = URL(string: "http://xx.xxx.xx.xxx:443/get")
        guard let requestUrl = url else { fatalError() }

        // Create URL Request
        var request = URLRequest(url: requestUrl)
        

        // Specify HTTP Method to use
        
        request.httpMethod = "GET"
        

        // Send HTTP Request
        let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
            
            // Check if Error took place
            if let error = error {
                print("Error took place \(error)")
                return
            }
            
            // Read HTTP Response Status code
            if let response = response as? HTTPURLResponse {
                print("Response HTTP Status code: \(response.statusCode)")
            }
            
            
            
            // Convert HTTP Response Data to a simple String
            if let data = data, let dataString = String(data: data, encoding: .utf8) {
                print("Response data string:\n \(dataString)")
                
                let decoder = JSONDecoder()
                
                
                do {
                    let taskItem = try decoder.decode([TaskData].self, from: data)
                    
                    
                    self.userData = taskItem
                } catch {
                    print(error)
                }
                
                
                
                
            }
            
        }
        task.resume()
    }
}

ShadowHawwk
  • 29
  • 1
  • 3
  • Does this answer your question? [debugDescription: "Expected to decode Array but found a dictionary instead.", underlyingError: nil)](https://stackoverflow.com/questions/50179922/debugdescription-expected-to-decode-arrayany-but-found-a-dictionary-instead) – Joakim Danielson Dec 29 '20 at 09:36

1 Answers1

0

Your root is a dictionary not an array , so add

struct Root : Codable {
  let result: [TaskData]
}

then

let res = try decoder.decode(Result.self, from: data)m 
self.userData = res.result
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87