Ios 从NSArray读取特定的JSON
这是我从openweathermap-API获得的JSON对象:Ios 从NSArray读取特定的JSON,ios,json,swift,web-applications,Ios,Json,Swift,Web Applications,这是我从openweathermap-API获得的JSON对象: ["main": { humidity = 12; pressure = 922; temp = "271.13"; "temp_max" = "171.15"; "temp_min" = "291.15"; }, "name": mycity, "id": 299129219, "coord": { lat = "92.1211"; lon = "182.1211"; },
["main": {
humidity = 12;
pressure = 922;
temp = "271.13";
"temp_max" = "171.15";
"temp_min" = "291.15";
}, "name": mycity, "id": 299129219, "coord": {
lat = "92.1211";
lon = "182.1211";
}, "weather": <__NSArrayI 0x1c042e820>(
{
description = "light snow";
icon = 13n;
id = 120;
main = Snow;
},
{
description = mist;
icon = 50n;
id = 722;
main = Mist;
}
)
, "clouds": {
all = 12;
}, "dt": 211, "base": stations, "sys": {
country = XXX;
id = 4891;
message = "0.02221";
sunrise = 1221122112;
sunset = 4343344343;
type = 1;
}, "cod": 100, "visibility": 3200, "wind": {
speed = 3;
}]
上面的代码运行良好,但我在读取第一个天气元素的描述时遇到了大量问题(称为“小雪”)
:
。。。似乎根本不起作用
那么我如何解决这个问题呢
提前感谢您。也使用了此API:)
这对我很有用:
guard let weathersArray = json["weather"] as? [[String: Any]],
let weatherJson = weathersArray.first,
let description = weatherJson["description"] as? String
else { return }
更新:如果需要所有数组元素,只需在weathersArray上循环并获取所有描述。
result[“weather”]
是字典数组,而不是字典。在使用JSON时,不要强制强制转换。您不能假设总是以特定的格式返回特定的数据。进行防御性编码,否则你的应用程序将崩溃。请使用Decodable进行解码
let description = (result["weather"] as! [String:Any]).first["description"]! //(result should be : "light snow")
guard let weathersArray = json["weather"] as? [[String: Any]],
let weatherJson = weathersArray.first,
let description = weatherJson["description"] as? String
else { return }