json - Swift NSMutableDictionary 解析 json 失败

标签 json swift alamofire nsmutabledictionary

我在 NSMutableDictionary 和 Alamofire 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” key ?我无法像这样解析json?有人告诉我尝试 SwiftyJSON,这种方式根本不可能。所有这些问题都是在我更新到 Xcode 7.3 和 cocoapods 1.0.0 后发生的。

最佳答案

基础集合类型不包含类型信息,并且可变版本 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,这意味着该值将在每次迭代中被覆盖。

关于json - Swift NSMutableDictionary 解析 json 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37391975/

相关文章:

iphone - Objective-C JSON 解析错误

java - ObjectMapper 无法反序列化 - 无法反序列化 START_ARRAY token 之外的 .... 实例

java - 使用 Gson 在 Java 中反序列化任意 JSON 并尊重整数

swift - 使用 Firebase 存储数据库填充 TableView

ios - 带文件上传的摘要式身份验证

ios - 如何使用 post 方法从登录功能将 JSON 数据传递到另一个 View Controller ?

javascript - 如何使用 jquery 在运行时创建 json 对象数组?

swift - 在swift中计算从单词到字符串结尾的字符串范围

ios - 如何在电子邮件正文中制作文本 "bold"

json - 在 Swift 中使用 Alamofire 发送包含字典对象数组的字典对象时,会发生奇怪的行为吗?