2016-05-23 180 views
0

我有一些奇怪的解析問題與NSMutableDictionary和Alomafire json響應。swift NSMutableDictionary解析json失敗

Alamofire.request(.POST, "\(Constants.apiUrl)/get_stuff", parameters: mapData, encoding:.JSON) 
    .responseJSON { response in 

     switch response.result { 
     case .Success(let data): 
      let info = data as! NSMutableDictionary 

      self.deleteCategoryFromCoreData() 

      if let categoryArray = info["category"] as? NSArray{ 
       for var i = 0; i < categoryArray.count; i++ { 
        self.categoryID = categoryArray[i]["id"] as? Int <-- error here 
        self.categoryName = categoryArray[i]["name"] as? NSString 
        self.saveCategoryDataToCoreData() 
       } 
      } 

我不知道爲什麼失敗:

(lldb) po categoryArray[i]["id"] 
2016-05-23 20:59:56.892 MyProject[9799:5005782] -[__NSCFNumber length]: unrecognized selector sent to instance 0xb000000000000013 
error: Execution was interrupted, reason: internal ObjC exception breakpoint(-3).. 
The process has been returned to the state before expression evaluation. 

但這並不失敗:

(lldb) po categoryArray[i]["name"] 
▿ Optional<String> 
    - Some : "Animals" 

下面是數據:

(lldb) po categoryArray[i] 
▿ 2 elements 
    ▿ [0] : 2 elements 
    - .0 : id 
    ▿ [1] : 2 elements 
    - .0 : name 
    - .1 : Animals 

爲什麼不能我訪問「id」鍵?我無法像這樣解析json?我被告知要嘗試SwiftyJSON,這種方式根本不可能。所有這些問題發生在我更新到xcode 7.3和cocoapods 1.0.0之後。謝謝。請幫忙 ?

回答

1

基礎集合類型不包含類型信息,可變版本NSMutableArrayNSMutableDictionary根本與Swift對應關係無關。

使用SWIFT原生類型的一切

Alamofire.request(.POST, "\(Constants.apiUrl)/get_stuff", parameters: mapData, encoding:.JSON) 
    .responseJSON { response in 

    switch response.result { 
    case .Success(let data): 
     let info = data as! [String:AnyObject] 

     self.deleteCategoryFromCoreData() 

     if let categoryArray = info["category"] as? [[String:AnyObject]] { 
     for category in categoryArray { 
      self.categoryID = category["id"] as? Int 
      self.categoryName = category["name"] as? String 
      self.saveCategoryDataToCoreData() 
     } 
     } 

如果你仍然可以獲得比鍵id值的誤差是一個字符串

if let id = category["id"] as? String { 
    self.categoryID = Int(id) 
} 

PS:考慮到你指定的重複所有值分別循環到相同變量categoryIDcategoryName,這意味着該值將在每次迭代中被覆蓋。