【问题标题】:I am getting nil while parsing JSON with Swift使用 Swift 解析 JSON 时我得到了 nil
【发布时间】: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 响应的图像而不是文本,这使得我们更难为您提供帮助。

标签: json swift parsing


【解决方案1】:

我修好了!谢谢你的所有建议。赞赏!

import UIKit

类视图控制器:UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.

    struct DataSource: Codable {
        let status: String?
        let totalResults: Int?
        let articles: [Articles]
    }

    struct Articles: Codable {
        let source: Source
        let author: String
        let title: String
    }

    struct Source: Codable {
        let id: String?
        let name: String
    }

    let source = URL(string: "http://newsapi.org/v2/everything?q=bitcoin&from=2020-03-30&sortBy=publishedAt&apiKey=XXXXXX")!
    URLSession.shared.dataTask(with: source) { (data, response, error ) in

        do
        {
            let publishing = try JSONDecoder().decode(DataSource.self, from: data!)

            print(publishing)
        }
        catch
        {
            print(error)
        }



    } .resume()


}

}

【讨论】:

    【解决方案2】:

    我在操场上做这个例子

    import UIKit
    import PlaygroundSupport
    
    
    // MARK: - ProfileResponse
    struct ArticlesResponse: Codable {
        var status: String
        var totalResults: Int
        var articles: [Article]
    }
    
    // MARK: - ProfileArticle
    struct Article: Codable {
        var source: Source
        var author: String?
        var title, articleDescription: String
        var url: String
        var urlToImage: String?
        var publishedAt: String
        var content: String?
    
        enum CodingKeys: String, CodingKey {
            case source, author, title
            case articleDescription = "description"
            case url, urlToImage, publishedAt, content
        }
    }
    
    // MARK: - ProfileSource
    struct Source: Codable {
        var id: String?
        var name: String
    }
    
    
    class MyViewController : UIViewController {
        override func loadView() {
            let view = UIView()
            view.backgroundColor = .white
    
            let label = UILabel()
            label.frame = CGRect(x: 150, y: 200, width: 200, height: 20)
            label.text = "Hello World!"
            label.textColor = .black
    
            view.addSubview(label)
            self.view = view
    
            if let url = URL(string: "http://newsapi.org/v2/everything?q=bitcoin&from=2020-03-30&sortBy=publishedAt&apiKey=f0b7d2e59beb4bcdb7a737a25c3542bc") {
               URLSession.shared.dataTask(with: url) { data, response, error in
                  if let data = data {
                      do {
                         let decoder = JSONDecoder()
                         let data = try decoder.decode(ArticlesResponse.self, from: data)
                        label.text = "\(data.status)"
                      } catch let error {
                         print(error)
                      }
                   }
               }.resume()
            }
        }
    }
    // Present the view controller in the Live View window
    PlaygroundPage.current.liveView = MyViewController()
    

    【讨论】:

    • Enzo,你认为我可以在操场上运行我的代码还是必须将它作为一个项目运行?
    • Playground 是学习 Swift 语言的好地方,但是当你开始使用 UI 时需要使用一个项目。我只是用 Playground 来举例说明一些具体的东西,并在一分钟内证明代码。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-02
    • 2020-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多