How do I fix error: "Expected to decode Dictionary<String, Any> but found an array instead" in this code?

How do I fix error: "Expected to decode Dictionary<String, Any> but found an array instead" in this code?

import UIKit

class ViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()

    //API Key: 5ca10b2d20a545099a108a3aeceb329c
    //url: https://newsapi.org/v2/top-headlines?country=us&apiKey=5ca10b2d20a545099a108a3aeceb329c


    // model

    struct Source: Decodable {
        var id: String
        var name: String
    }

    struct Articles: Decodable {
        var source: Source
        var author: String
        var title: String
        var description: String
        var url: String
        var urlToImage: String
        var publishedAt: String
        var content: String

    }

    struct JSONDescription: Decodable {
        var status: String
        var totalResults: Int
        var articles: Articles
    }


    guard let url = URL(string: "https://newsapi.org/v2/top-headlines?country=us&apiKey=5ca10b2d20a545099a108a3aeceb329c") else { return }


    URLSession.shared.dataTask(with: url) { data, response, error in

        guard let data = data else { return }

        //let dataAsString = String(data: data, encoding: .utf8)
//            print(dataAsString)

        do {
        let jsonDescription = try JSONDecoder().decode(JSONDescription.self, from: data)
            print(jsonDescription.totalResults)
        }
        catch let jsonError {
            print("Json Error:", jsonError)
        }
}.resume()
}
}

我希望看到的是此处返回的 JSON 数据:https://newsapi.org/v2/top-headlines?country=us&apiKey=5ca10b2d20a545099a108a3aeceb329c

您可以将其放入此格式化程序中以使其可读:https://jsonformatter.curiousconcept.com

我认为我做的一切都是正确的。我的模型建错了吗?我不确定如何修复此错误。

所以,借助返回的错误,再看数据,好像"articles"是一个数组。

这是我要尝试的方法:

  • 将您的 Articles 结构重命名为 Article
  • 将 JSONDescription 的 articles 属性 从 Articles 更改为 [Article]

我没有注意到数据映射中的任何其他错误,但希望这能让你更接近。