我正在尝试以 Dictionary
的形式解析 JSON 数据。但是,字典作为数组作为另一个字典的值放在一起。更糟糕的是,API 给出的唯一键是第三级值(即字典数组)。知道如何获取一级字典中的数据吗?
代码尝试:
if let valueTripleDictionary = jsonDataDictiony["value"] as? [String : AnyObject]
{
if let valueDoubleDictionary = valueTripleDictionary as? [String : AnyObject]
{
if let valueDictionary = valueDoubleDictionary as? [String : AnyObject]
{
self.busStopCode = valueDictionary["BusStopCode"] as? String
self.roadName = valueDictionary["RoadName"] as? String
self.busStopDescription = valueDictionary["Description"] as? String
self.busStopLatitude = valueDictionary["Latitude"] as? Double
self.busStopLongitude = valueDictionary["Longitude"] as? Double
print(busStopCode)
print(roadName)
print(busStopDescription)
print(busStopLatitude)
print(busStopLongitude)
}
}
}
这是一段JSON数据
["value": <__NSArrayI 0x7fe884d24f00>(
{
BusStopCode = 01012;
Description = "Hotel Grand Pacific";
Latitude = "1.29684825487647";
Longitude = "103.8525359165401";
RoadName = "Victoria St";
},
{
BusStopCode = 01013;
Description = "St. Joseph's Ch";
Latitude = "1.29770970610083";
Longitude = "103.8532247463225";
RoadName = "Victoria St";
}
)
]
最佳答案
value
键包含Array
而不是Dictionary
,因此您需要编写[[String : AnyObject]]
而不是 [String : AnyObject]
。
if let array = jsonDataDictiony["value"] as? [[String : AnyObject]] {
for dic in array {
print(dic["BusStopCode"]) //Access other values same way
}
}
关于arrays - 如何从嵌入字典中的数组中解析 JSON 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40155022/