【发布时间】:2020-06-10 16:18:20
【问题描述】:
当我尝试运行我的代码时出现此错误,因为我不知道如何访问 json 文件的 id。
当我运行我的代码时,我得到了这个错误:
keyNotFound(CodingKeys(stringValue: "id", intValue: nil), Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "articles", intValue: nil), _JSONKey(stringValue: "Index 0", intValue: 0)], debugDescription: "No value associated with key CodingKeys(stringValue: \"id\", intValue: nil) (\"id\").", underlyingError: nil))
这是我从 API 检索数据的代码
func fetchData() {
if let url = URL(string: "https://newsapi.org/v2/top-headlines?country=gb&category=science&apiKey=7806d7a294994cd2af9d272bbfe4f334") {
let session = URLSession(configuration: .default)
let task = session.dataTask(with: url) { (data, response, error) in
if error == nil {
let decoder = JSONDecoder()
if let safeData = data {
do {
let results = try decoder.decode(Results.self, from: safeData)
// Update must happen on the main thread, not in the background
DispatchQueue.main.async {
self.posts = results.articles
}
} catch {
print(error.localizedDescription)
}
}
}
}
task.resume()
}
}
这里是 postData 代码:
struct Results: Decodable {
let articles: [Post]
}
struct Post: Decodable, Identifiable {
var id: String
let title: String
let url: String
}
最后,这是我应该在屏幕上呈现数据的代码:
struct ContentView: View {
@ObservedObject var networkManager = NetworkManager()
var body: some View {
NavigationView {
// for every single post in the post array
List(networkManager.posts) { post in
Text(post.title)
}
.navigationBarTitle("Science Bite")
}
// This calls fetch data
.onAppear {
self.networkManager.fetchData()
}
}
}
【问题讨论】:
-
您错过了
source步骤,您可以在其中找到id。这就是说的错误。如果您对 JSON 进行格式化,您会发现id与title和url不在同一级别。要么为自己添加另一个结构,要么为该嵌套使用自定义 init。