无法从 JSON 中获取值(无法将类型“__NSCFNumber”(0x7fff87b9c520)的值转换为“NSDictionary”(0x7fff87b9d5b0))
Posted
技术标签:
【中文标题】无法从 JSON 中获取值(无法将类型“__NSCFNumber”(0x7fff87b9c520)的值转换为“NSDictionary”(0x7fff87b9d5b0))【英文标题】:Can't get the value from the JSON (Could not cast value of type '__NSCFNumber' (0x7fff87b9c520) to 'NSDictionary' (0x7fff87b9d5b0)) 【发布时间】:2019-12-01 19:11:54 【问题描述】:我刚刚开始编程,我遇到了从 JSON 中提取参数的问题。
这是 JSON 文件的样子:
"results": 1,
"data": [
"wind":
"degrees": 220,
"speed_kts": 4,
"speed_mph": 5,
"speed_mps": 2
,
"temperature":
"celsius": 13,
"fahrenheit": 55
,
"dewpoint":
"celsius": 12,
"fahrenheit": 54
,
"humidity":
"percent": 94
,
"barometer":
"hg": 29.85,
"hpa": 1011,
"kpa": 101.09,
"mb": 1010.92
,
"visibility":
"miles": "Greater than 6",
"miles_float": 6.21,
"meters": "10,000+",
"meters_float": 10000
,
"elevation":
"feet": 98.43,
"meters": 30
,
"location":
"coordinates": [
-6.06011,
36.744598
],
"type": "Point"
,
"icao": "LEJR",
"observed": "2019-12-01T18:00:00.000Z",
"raw_text": "LEJR 011800Z 22004KT 9999 FEW020 13/12 Q1011",
"station":
"name": "Jerez"
,
"clouds": [
"code": "FEW",
"text": "Few",
"base_feet_agl": 2000,
"base_meters_agl": 609.6
],
"flight_category": "VFR",
"conditions": []
]
我想检索以 hPa 为单位的气压(结果 => 数据 => 气压计 => hpa)。
这是我的代码(我使用 Alamofire):
override func viewDidLoad()
super.viewDidLoad()
Alamofire.request("https://api.checkwx.com/metar/lejr/decoded", headers: headers).responseJSON response in
// print(response)
if let metardataJSON = response.result.value
let metarDataObject:Dictionary = metardataJSON as! Dictionary<String, Any>
print(metarDataObject)
let resultsObject:Dictionary = metarDataObject["results"] as! Dictionary<String, Any>
let dataObject:Dictionary = resultsObject["data"] as! Dictionary<String, Any>
let barometerObject:Dictionary = dataObject["barometer"] as! Dictionary<String, Any>
let hpaObject:NSNumber = barometerObject["hpa"] as! NSNumber
print(hpaObject)
经过所有尝试,我无法摆脱错误“线程 1:信号 SIGABRT”:
Could not cast value of type '__NSCFNumber' (0x7fff87b9c520) to 'NSDictionary' (0x7fff87b9d5b0).
2019-12-01 19:34:18.723588+0100 Metar[6721:452116] Could not cast value of type '__NSCFNumber' (0x7fff87b9c520) to 'NSDictionary' (0x7fff87b9d5b0).
谁能阐明这个问题并帮助我改进我的代码?
如果这个问题看起来简单或不恰当,请原谅我 - 我只是一个初学者:)
【问题讨论】:
不要那样做。使用可解码。 【参考方案1】:删除第一个提取行并参考第二行中的metarDataObject
。请注意,"data"
内部有一个数组:
let dataObject:Dictionary = metarDataObject["data"] as! [[String: Any]]
let barometerObject:Dictionary = dataObject[0]["barometer"] as! [String: Any]
let hpaObject:NSNumber = barometerObject["hpa"] as! NSNumber
为了将来不必处理这些类型的问题,我建议使用某种“对象映射”框架,该框架负责将 json 映射到可用的、类型安全的结构中。
【讨论】:
以上是关于无法从 JSON 中获取值(无法将类型“__NSCFNumber”(0x7fff87b9c520)的值转换为“NSDictionary”(0x7fff87b9d5b0))的主要内容,如果未能解决你的问题,请参考以下文章
nsnumber 类型的 json 值“2”无法转换为 nsstring
我无法从 python 中的 JSON API 响应中获取值
Swift JSON 错误,无法将类型“__NSArrayM”(0x507b58)的值转换为“NSDictionary”(0x507d74)