如何在swift4中解析和获取小而复杂的json数据?
我需要帮助解析名为weather.json的json文件。 weather.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",
{
"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")
}