我試圖解析看起來像這樣的JSON時遇到的問題確實需要幫助: http://imgur.com/t39nUSv 這是一個字典'{}'的數組'[]',每個字典都有兩個鍵/值對,如圖所示。 這是我的代碼,我不知道爲什麼它崩潰上線無法將'__NSCFArray'類型的值轉換爲'NSDictionary'+在地圖視圖中顯示註釋
for location in JSON as! Dictionary<String, AnyObject>
這裏是一個真實使代碼會崩潰
func populateMapObjects() {
if populatingMapObjects {
return
}
populatingMapObjects = true
self.loadingIndicator.startAnimating()
Alamofire.request(GWNetworking.Router.MapObjects).responseJSON() { response in
if let JSON = response.result.value {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0)) {
if (JSON .isKindOfClass(NSArray)) {
for location in JSON as! Dictionary<String,AnyObject> {
if let issueLocation: IssueLocation = IssueLocation(locationName: "Center of the universe", campusName: "Queen's University", latitude: 44.22661586877309, longitude: -76.49380087852478, coordinate: CLLocationCoordinate2D(latitude: 44.22661586877309, longitude: -76.49380087852478)) {
var index = 0
if let locationName = JSON[index]["name"] as? String {
issueLocation.locationName = locationName
}
print(issueLocation.locationName)
if let latitude = JSON[index]["coordinates"]!![1] as? Double {
issueLocation.latitude = latitude
}
if let longitude = JSON[index]["coordinates"]!![0] as? Double {
issueLocation.longitude = longitude
}
issueLocation.coordinate = CLLocationCoordinate2D(latitude: issueLocation.latitude, longitude: issueLocation.longitude)
index++
self.mapObjects.addObject(issueLocation)
}
}
}
dispatch_async(dispatch_get_main_queue()) {
self.loadingIndicator.stopAnimating()
self.populatingMapObjects = false
}
}
}
}
}
我真的很困惑關於是否我應該將JSON的每個「層」視爲一個數組或字典,如果它應該是NSDictionary,Dictionary ..並且如果我應該使用索引或valueForKey ....我迷路了。有人請告訴我如何解決這個錯誤。 我爲應用程序的其他部分使用了相同的API,但此視圖尤其會得到一個看起來不同的JSON,這就是爲什麼我無法讓我的代碼工作。
編輯1:將註釋添加到地圖視圖的代碼。
func loadObjectsIntoMapView() {
for mapObject in mapObjects {
let temporaryMapAnnotation = IssueLocation(locationName: mapObject.locationName, campusName: "Main Campus", latitude: mapObject.latitude, longitude: mapObject.longitude, coordinate: mapObject.coordinate)
if (temporaryMapAnnotation.longitude < -76.50921821594238) {
temporaryMapAnnotation.campusName = "West Campus"
}
self.mapView.addAnnotation(temporaryMapAnnotation)
}
}
它看起來像座標是一個數組 – user523234
是啊,這就是爲什麼我使用索引來獲取經度和緯度值。是否有什麼錯? –