Alamofire JSON序列化错误-Swift 2.0



我在通过Alamofire发布JSON时遇到问题。我得到下面的错误。我的参数如前所述——你知道我做错了什么吗?

    let parameters: [String: AnyObject] = [
        "t": [
            "name": "foo",
            "event": "tap",
            "ts":  NSDate().timeIntervalSince1970
        ],
        "z": [["key": "12345"], ["key": "67890"]]
    ]
Alamofire.request(.POST, "https://myapi.com/test", parameters: parameters, encoding: .JSON)

错误域=com.alamofire.Error代码=-6006"无法序列化JSON。输入数据为零或零长度。"UserInfo={NSLocalizedFailureReason=JSON无法序列化。输入数据是零或零长。}

NSDate不是有效的JSON对象。您需要使用NSDateFormatter使用许多RFC或ISO规范之一将其转换为字符串(很可能)。下面是一个ISO8601日期的示例。

let dateFormatter = NSDateFormatter()
dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
let iso8601String = dateFormatter.stringFromDate(NSDate())

使用此逻辑,您首先需要将NSDate参数转换为String,然后将String版本添加到参数字典中,Alamofire将从中处理它。

相关内容

最新更新