我正在尝试与API调用。我每次尝试做API调用时都会出错。
typeMismatch(斯威夫特。数组,Swift.DecodingError。上下文(codingPath: [], debugDescription: "期望解码数组,但发现一个字典。",底层错误:nil))
这是我在控制台模拟代码时看到的。
这是json格式,我试图在我的应用程序调用。点击
我的模型
struct Article: Codable {
let author: String
let title, articleDescription: String
let url: String
let urlToImage: String
let publishedAt: Date
let content: String?
enum CodingKeys: String, CodingKey {
case author, title
case articleDescription = "description"
case url, urlToImage, publishedAt, content
}
}
和This is my API Call function.
import UIKit
class ViewController: UIViewController {
var article = [Article]()
override func viewDidLoad() {
super.viewDidLoad()
jsonParse {
print("success")
}
view.backgroundColor = .red
}
func jsonParse(completed: @escaping () -> ()) {
let url = URL(string: "https://newsapi.org/v2/top-headlines?country=tr&apiKey=1ea9c2d2fbe74278883a8dc0c9eb912f")
let task = URLSession.shared.dataTask(with: url!) { data, response, error in
if error != nil {
print(error?.localizedDescription as Any)
}else {
do {
let result = try JSONDecoder().decode([Article].self, from: data!)
DispatchQueue.main.async {
print(data as Any)
print("success")
self.jsonParse {
print("success")
}
}
}catch {
print(error.localizedDescription)
}
}
}
task.resume()
}
}
你能帮我解决我的问题吗,谢谢。
这是一个非常常见的错误:您忽略了根对象,即字典。对于Decodable
,必须从顶部解码JSON。
添加结构体
struct Response: Decodable {
let status: String
let totalResults: Int
let articles: [Article]
}
和解码
let result = try JSONDecoder().decode(Response.self, from: data!)
从来和可编码捕获块中的print(error.localizedDescription)
。总是这样写
} catch {
print(error)
}