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()
}
}