Swift Alamofire中JSON写入的类型无效

时间:2016-06-25 17:12:28

标签: ios json swift swift2 alamofire

我在向Alamofire发送参数时遇到问题。这是服务器期望的JSON:

{
“users”:[{“_id”:”1234567”}, {“_id”:”665543”}]
}

现在,在我的Swift代码中,这就是我试图构建上述对象的方式:

let parameters = [“users” : users]
return sendRequest(.PUT, url: “example.com", parameters: parameters)

其中users是数组。这里有更多关于用户是什么的信息(我已经取出了一些其他的继承来简化):

class User : MyBase, CustomStringConvertible {
  var name: String

  var description : String {
     get{
          return ["_id" : self._id!].description
     }
 }
}

class MyBase {
  var _id: String?
}

如果我做了debugPrint(users),这就是我得到的:

[“users”: [["_id": "1234567"], ["_id": "665543"]]]

这是执行Alamofire内容的sendRequest方法:

static func sendRequest(method: Alamofire.Method, url: String, parameters: [String: AnyObject]?) {
        Alamofire.request(method, url, parameters: parameters as! [String: [User]], encoding: .JSON)
            .validate()
            .responseObject { (response: Response<User, NSError>) in
                switch response.result {
                case .Success(let value):
                    // do something
                case .Failure(let error):
                    // do something else
                }
        }
    }

它在Alamofire.request线上引发的错误是:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Invalid type in JSON write (MyApp.User)’

最终,我拥有的是一组用户对象,我需要以上面提到的JSON格式将其发送到我的服务器。作为Swift的新手,我一直在努力解决这个问题,所以任何帮助都会受到赞赏。

1 个答案:

答案 0 :(得分:1)

问题似乎出现在您的debugPrint(用户)中。您发送到服务器的是可选类型。您需要发送字符串

所以你有self._id将其改为self._id!

相关问题