Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/haskell/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在swift4中解析和获取小而复杂的json数据?_Json_Parsing_Codable_Decodable_Swift4.2 - Fatal编程技术网

如何在swift4中解析和获取小而复杂的json数据?

如何在swift4中解析和获取小而复杂的json数据?,json,parsing,codable,decodable,swift4.2,Json,Parsing,Codable,Decodable,Swift4.2,我需要帮助解析名为weather.json的json文件。 weather.json { "weatherinfo": { "local": [ { "country": "Korea", "weather": "rainy", "temperature": "20" }, { "country": "US",

我需要帮助解析名为weather.json的json文件。 weather.json

{
  "weatherinfo": {
        "local": [
          {
            "country": "Korea",
            "weather": "rainy",
            "temperature": "20"
          },
          {
            "country": "US",
            "weather": "sunny",
            "temperature": "30"
          }
        ]
  }
}
这是我的密码

struct Weather: Decodable {
    var weatherInfo: WeatherInfo?
}

struct WeatherInfo: Decodable {
    let local: [Local]?
}

struct Local: Decodable {
    let country: String?
    let weather: String?
    let temperature: String?
}
UIViewController中的内置func viewDidLoad

我成功解析了,但无法从天气常数中获取数据。。 如何从json文件中获取国家/地区值。。? 有人能修好我的代码吗?。

首先,读取捆绑包中的文件的URLSession太过了。只需要获取数据

第二,声明所有内容都是非可选的,因为您清楚地知道所有密钥都是可用的

struct Weather: Decodable {
    let weatherinfo: WeatherInfo // note the lowercase spelling
}

struct WeatherInfo: Decodable {
    let local: [Local]
}

struct Local: Decodable {
    let country: String
    let weather: String
    let temperature: String
}
国家/地区位于weatherInfo的本地阵列中

struct Weather: Decodable {
    let weatherinfo: WeatherInfo // note the lowercase spelling
}

struct WeatherInfo: Decodable {
    let local: [Local]
}

struct Local: Decodable {
    let country: String
    let weather: String
    let temperature: String
}
let url = Bundle.main.url(forResource: "weather", withExtension: "json")!
let data = try! Data(contentsOf: url)
let result = try! JSONDecoder().decode(Weather.self, from: data)
for location in result.weatherinfo.local {
    print("In \(location.country) the weather is \(location.weather) and the temperature is \(location.temperature) degrees")
}