【发布时间】:2020-04-29 23:48:30
【问题描述】:
我正在学习 Swift,我正在学习解析 JSON。我有一个有点复杂的 API,我无法从中获取数据。你能告诉我我在下面犯了什么错误吗?
import UIKit
struct DataSource: Codable {
let status: Int
let totalResults: String
let articles: [Articles]
}
struct Articles: Codable {
let source: [Source]
let author: String
let title: String
}
struct Source: Codable {
let name: String
}
let source = URL(string: "http://newsapi.org/v2/everything?q=bitcoin&from=2020-03-29&sortBy=publishedAt&apiKey=51480e6fd4294010d")!
URLSession.shared.dataTask(with: source) { (data, response, error ) in
if let data = data {
let publishing = try? JSONDecoder().decode([DataSource].self, from: data)
print(publishing)
}
}.resume()
【问题讨论】:
-
一些错误:您使用的是
try?而不是try,这意味着您忽略了任何错误,这是一个非常糟糕的错误,您期待一个 DataSource 数组,但它似乎是一个单个实例,您已在发布的代码中包含您的 pivate api 密钥,因此现在任何人都可以使用它,您发布了您的 json 响应的图像而不是文本,这使得我们更难为您提供帮助。