JSON 请求未返回数据

标签 json swift

我正在尝试创建一个天气应用程序。我遵循了有关 JSON 和 Swift 4 Decodable 的教程,我遵循了该教程并且它有效。问题是,当我尝试使用自己的 URL 来发出请求时,它不起作用。 这是我的代码:

class MainVC: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    let jsonUrlString: String = "https://api.darksky.net/forecast/APIKEY/37.8267,-122.4233"

    private func getForecast(){
        guard let url = URL(string: jsonUrlString) else { return }
        URLSession.shared.dataTask(with: url) { (data, response, err) in
            guard let data = data else { return }
            do{
                let weatherForecast = try JSONDecoder().decode(Weather.self, from: data)
                print(weatherForecast)
            }catch _ as NSError{

            }
            }.resume()
    }
}

错误日志:

Error Domain=NSCocoaErrorDomain Code=4864 "Expected to decode Array<Any> but found a dictionary instead." UserInfo={NSCodingPath=(
), NSDebugDescription=Expected to decode Array<Any> but found a dictionary instead.}

我如何解析这个 https://darksky.net/dev/docs#forecast-request ?我只需要 Daily 部分中的一些内容,但对我来说它就像一个数组中的数组。

最佳答案

看起来您的天气结构构建不正确。它应该看起来像这样:

struct DataItem: Codable {
    var summary: String
    var uvIndex: Int    
}

struct Info: Codable {
    var summary: String
    var icon: String
    var data: [DataItem]
}

struct Weather: Codable {
    var daily: Info
    var hourly: Info
    var timezone: String
}

我遗漏了很多项目,但这应该可以帮助您入门。

关于JSON 请求未返回数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53469641/

相关文章:

c# - 如何在 C# 中遍历复杂的嵌套 Json 并将一组值附加到同一个 Json 中

ios - 如何使用 JSONDecoder 获取推文

ios - 使用未解析的标识符 CNContact [swift 3]

swift - Swift 中 UInt64 按位运算崩溃

使用 JavaScript 对象字面量表示法的 JavaScript 构造函数

从 json 转换的 C# 问题

jquery - 为什么 JSON 数据没有立即加载到我的 HTML 页面中?

ios - 使用 FSCalendar 的事件表

ios - 如何在 SwiftUI View 中访问自己的窗口?

php - AFNetworking 2.0 POST 问题,Cocoa 错误 3840(JSON 文本没有以数组开头...)