Swift:无法使用NSObjects将'NSNull'类型的值转换为'NSDictionary'

时间:2015-10-31 19:21:25

标签: ios json swift alamofire

Swift 2.1 Xcode 7.1 Alamofire 2.0.2

通过我在下面描述的Alamofire功能,我正在从API中检索JSON格式的传单列表:

Alamofire.request(Router.GetList()).responseJSON { (_, _, result) in
      var flyers = [Flyer]()

      switch result {
        case .Success(let json):
          if let responseObject = json as? [String: AnyObject], let hits = responseObject["hits"] as? [[String: AnyObject]] {
print(hits)
            for dictionary in hits {
              flyers.append(Flyer(dictionary: dictionary))
            }

            completionHandler(flyers, nil)
          }
        case .Failure(_, let error):
          completionHandler(nil, error as NSError)
      }
    }

打印(点击)产生的JSON响应是:

[["title": Code 103, 
 "event": {
    "_id" = 54b0561f274441073751;
    name = "Code 103";
    }
],
["title": Code 104, 
 "event": {
    "_id" = 54b0561f274441073752;
    name = "Code 104";
    }
]]

如下所示,Flyer类有一个属性(“event”),它引用了类Event id and name的两个属性:

class Flyer: NSObject{

  var title: String?
  var event: Event?

  init(dictionary: [String: AnyObject]) {
    title    = dictionary["title"] as? String
    event    = Event(dictionary: dictionary["event"] as! [String: AnyObject])
  }
}

class Event: NSObject{

  var id: String?
  var name: String?

  init(dictionary: [String: AnyObject]){

    id              = dictionary["id"] as? String
    name            = dictionary["name"] as? String
  }
}

我得到了下一个错误:

Could not cast value of type 'NSNull' (0x107d50378) to 'NSDictionary' (0x107d4fd60).

此错误位于Flyer类中:

event    = Event(dictionary: dictionary["event"] as! [String: AnyObject])

我不知道如何解决这个问题,因为响应不是空的。感谢帮助

1 个答案:

答案 0 :(得分:0)

以下在游乐场中完美运行:尝试干净并重建。

let json: AnyObject = [
    "hits": [
        [
            "title": "Code 103",
            "event": [
            "_id": "54b0561f274441073751",
            "name": "Code 103"
            ]
        ],
        [
            "title": "Code 104",
            "event": [
                "_id": "54b0561f274441073752",
                "name": "Code 104"
            ]
        ]
    ]
]

class Flyer: NSObject{

    var title: String?
    var event: Event?

    init(dictionary: [String: AnyObject]) {
        title = dictionary["title"] as? String
        event = Event(dictionary: dictionary["event"] as! [String: AnyObject])
    }
}

class Event: NSObject{

    var id: String?
    var name: String?

    init(dictionary: [String: AnyObject]){

        id = dictionary["id"] as? String
        name = dictionary["name"] as? String
    }
}

var flyers = [Flyer]()

if let responseObject = json as? [String: AnyObject], let hits = responseObject["hits"] as? [[String: AnyObject]] {
    print(hits)
    for dictionary in hits {
        flyers.append(Flyer(dictionary: dictionary))
    }
}