ios - 在 Swift Alamofire 中写入的 JSON 类型无效

标签 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 的新手,我一直在努力解决这个问题,因此非常感谢您的帮助。

最佳答案

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

因此,如果您有 self._id,请将其更改为 self._id!

关于ios - 在 Swift Alamofire 中写入的 JSON 类型无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38030943/

相关文章:

ios - 无法从数据库中检索评论 (FIREBASE/IOS)

iphone - 如何从 View 中关闭键盘?

ruby-on-rails - Rails Controller 中的默认序列化程序渲染选项

objective-c - Swift 语言中的 UITabBarController、UINavigationController 和 UIViewController 间距

iphone - 如何禁用使用 -startMonitoringForRegion 注册的任何 CLRegion 对象?

ios - 将 UIRefreshControl 添加到 UIScrollView

python - Pickle 拒绝使用 celery 报告 ContentDisallowed : Refusing to deserialize untrusted content of type pickle 来序列化内容

javascript - 如何从对象中检索数据并将其存储到数组中

objective-c - Swift - SCNVector4 到 NSValue 的数组?

arrays - 有没有一种方法可以在使用方法名称时迭代 Swift 中的元素?