繁体   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