簡體   English   中英

為什么我無法解析以下 json?

[英]Why I can't parse the following json?

我有我需要解析的 json 響應,根據https://newsapi.org網站,應該如下所示:

{
    "status": "ok",
    "totalResults": 4498,
    "articles": [{
        "source": {
            "id": null,
            "name": "Techweekeurope.co.uk"
        },
        "author": null,
        "title": "Top ten cloud service providers for reliability and price",
        "description": "In a time where the reliability and stability of cloud service providers comes into spotlight, we pick our top ten that will help you propel your business to the next level. We recently talked about building your own local network with a Raspberry Pi starter …",
        "url": "https://www.techweekeurope.co.uk/top-ten-cloud-service-providers-reliability-price/",
        "urlToImage": "https://www.techweekeurope.co.uk/wp-content/uploads/2020/01/Cloud-Service-Providers.gif",
        "publishedAt": "2020-01-04T16:17:00Z",
        "content": "In a time where the reliability and stability of cloud service providers comes into spotlight, we pick our top ten that will help you propel your business to the next level. We recently talked about building your own local network with a Raspberry Pi starter … [+4441 chars]"
    }, ...]
}

我創建了用於解析它的結構

import Foundation

struct Article: Codable {
    var source: Source
    var author: String?
    var title: String
    var description: String
    var url: URL
    var urlToImage: URL?
    var content: String

    enum codingKeys: String, CodingKey {
        case source
        case author
        case title
        case description
        case url
        case urlToImage
        case content
    }
}

struct Source: Codable {
    var name: String

}

struct Articles: Codable {
    var articles: [Article]
}

我創建了類網絡服務類

class NetworkService {

    // MARK: - Methods
    func parseJSON(from url: URL) {

        let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
            do {
                let decoder = JSONDecoder()

                let articleData = try decoder.decode(Articles.self, from: data!)
                print(articleData.articles.description)
            } catch {
                print(error)
            }
        }
        task.resume()
    }
}

在控制台我有這個:

keyNotFound(CodingKeys(stringValue: "articles", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key CodingKeys(stringValue: \\"articles\\", intValue: nil) (\\ “文章\\”)”,underlyingError: nil))

您的錯誤告訴您 JSON 有效,但在響應中找不到任何articles鍵。

我建議在您對Articles的定義中包含statusmessage ,並使articles屬性成為可選屬性。 status可能不是"ok" 無論如何, articles顯然是缺席的。

struct Articles: Codable {
    let articles: [Article]?
    let status: String
    let message: String?
    let code: String?
}

例如,如果您不提供有效的密鑰,您將收到類似

{
    "status": "error",
    "code": "apiKeyInvalid",
    "message": "Your API key is invalid or incorrect. Check your key, or go to https://newsapi.org to create a free API key."
}

您可能希望通過將其設為可選來處理出現錯誤時articles可能不存在的情況。


無關,但強制解包data操作符是危險的。 如果您有一些網絡錯誤,您的應用程序將崩潰。 我建議打開它,例如:

func parseJSON(from url: URL) {

    let task = URLSession.shared.dataTask(with: url) { data, response, error in
        guard let data = data, error == nil else {
            print(error ?? "Unknown error")
            return
        }

        do {
            let articleData = try JSONDecoder().decode(Articles.self, from: data)
            guard let articles = articleData.articles else {
                print("No articles", articleData.status, articleData.message ?? "No message")
                return
            }

            for article in articles {
                print(article.description)
            }
        } catch {
            print(error)
        }
    }
    task.resume()
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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