xcode “预期解码数组< Any>,但找到的却是字典,”如何解决此问题

ulmd4ohb  于 2022-12-14  发布在  其他
关注(0)|答案(1)|浏览(180)

我正在尝试使用API调用。每次尝试使用API调用时都出现错误。

typeMismatch(斯威夫特.数组,斯威夫特.解码错误.上下文(编码路径:[],调试描述:“应解码数组,但找到的是字典。",underlyingError:无))

这是我在控制台中模拟代码时看到。
下面是我在应用程序中尝试调用的json格式。Click

我的模型

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

这是我的API调用函数。

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

你能帮我解决一下我的问题吗,谢谢。

zsbz8rwp

zsbz8rwp1#

这是一个很常见的错误:忽略根对象,一个字典,对于Decodable,必须从顶部解码JSON。
添加此结构

struct Response: Decodable {
    let status: String
    let totalResults: Int
    let articles: [Article]
}

及解码了

let result = try JSONDecoder().decode(Response.self, from: data!)

neverprint(error.localizedDescription)在一个可编码的catch块中。

} catch {
    print(error)
}

相关问题