[英]Trying to return a value from API with JSON
我試圖從 newsapi.org/ 獲取數據。
parseJSON 返回錯誤,由於某種原因它無法從 NewsData 獲取數據。
我認為我的 NewsData 屬性存在一些問題,其中 parseJSON func 無法找出數據。
這是 JSON(來自 urlString):
{
"status": "ok",
"totalResults": 38,
"articles": [
{
"source": {
"id": "fox-news",
"name": "Fox News"
},
"author": "Ryan Gaydos",
"title": "Errol Spence Jr. retains welterweight titles in victory over Danny Garcia - Fox News",
"description": "Errol Spence Jr. defeated Danny Garcia via unanimous decision Saturday night to retain the WBC and IBF welterweight titles.",
"url": "https://www.foxnews.com/sports/errol-spence-jr-danny-garcia-boxing-2020",
"urlToImage": "https://static.foxnews.com/foxnews.com/content/uploads/2020/12/Errol-Spence2.jpg",
"publishedAt": "2020-12-06T05:39:59Z",
"content": "Errol Spence Jr. defeated Danny Garcia via unanimous decision Saturday night to retain the WBC and IBF welterweight titles.\r\nThe judges scored the fight 116-112, 116-112, 117-111 in
favor of Spence.\r… [+1417 chars]"
}
]
}
這是我的代碼:
新聞數據.Swift:
struct NewsData: Codable {
let articles: [Article]
}
struct Article: Codable {
let title: String
let description: String
let content: String
}
新聞經理.Swift:
func getNews() {
let urlString = "\(baseURL)&apiKey=\(apiKey)"
if let url = URL(string: urlString){
let session = URLSession(configuration: .default)
let task = session.dataTask(with: url) { (data, response, error) in
if error != nil {
print(error)
} else {
if let safeData = data {
if let news = self.parseJSON(safeData) {
print(news)
}
}
}
}
task.resume()
}
}
func parseJSON(_ data: Data) -> String? {
let encoder = JSONDecoder()
do {
let encodedData = try encoder.decode(NewsData.self, from: data)
let des = encodedData.articles[0].content
let title = encodedData.articles[0].title
let content = encodedData.articles[0].content
return content
} catch {
print(error)
return nil
}
}
}
返回錯誤是:
valueNotFound(Swift.String, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "articles", intValue: nil), _JSONKey(stringValue: "Index 1", intValue: 1), CodingKeys(stringValue: "content", intValue: nil)], debugDescription: "Expected String value but found null instead.", underlyingError: nil))
DecodingError
是有史以來最精確和最容易理解的錯誤之一。
請完整閱讀。
valueNotFound(Swift.String, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "articles", intValue: nil), _JSONKey(stringValue: "Index 1", intValue: 1), CodingKeys(stringValue: "content", intValue: nil)], debugDescription: “預期的字符串值,但找到了 null。”,underlyingError: nil))
有三個重要信息:
What : valueNotFound
表示某處缺少值
其中: CodingPath
類似於鍵路徑,連接stringValue
的結果是:
articles[1].content
指向文章第二項中的屬性內容
原因: debugDescription
描述了實際錯誤:
Expected
表示錯誤的類型 → 非可選String
found
表示正確的類型 → <null>
不是值,需要可選類型解決方案:將content
聲明為可選
struct Article: Codable {
let title: String
let description: String
let content: String?
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.