簡體   English   中英

嘗試使用 JSON 從 API 返回一個值

[英]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))

有三個重要信息:

  1. What : valueNotFound表示某處缺少值

  2. 其中CodingPath類似於鍵路徑,連接stringValue的結果是:

     articles[1].content

    指向文章第二項中的屬性內容

  3. 原因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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM