I am getting an error when decoding JSON in swift 4.2
Expected to decode Array but found a dictionary instead.
My JSON Model:
public struct NewsSource: Equatable, Decodable {
public let id: String?
public let name: String?
public let sourceDescription: String?
public let url: URL?
enum CodingKeys: String, CodingKey {
case id
case name
case sourceDescription = "description"
case url
}
public init(id: String,
name: String,
sourceDescription: String,
url: URL,
category: NewsCategory,
language: NewsLanguage,
country: NewsCountry) {
self.id = id
self.name = name
self.sourceDescription = sourceDescription
self.url = url
} }
How I fetch the JSON:
func fetchJSON() {
let urlString = "https://newsapi.org/v2/sources?apiKey=myAPIKey"
guard let url = URL(string: urlString) else { return }
URLSession.shared.dataTask(with: url) { (data, _, err) in
DispatchQueue.main.async {
if let err = err {
print("Failed to get data from url:", err)
return
}
guard let data = data else { return }
print(data)
do {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
self.Sources = try decoder.decode([NewsSource].self, from: data)
self.tableView.reloadData()
} catch let jsonErr {
print("Failed to decode:", jsonErr)
}
}
}.resume()
}