【问题标题】:Invalid type in JSON write in Swift Alamofire在 Swift Alamofire 中写入的 JSON 中的类型无效
【发布时间】:2016-10-28 02:36:57
【问题描述】:

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

【问题讨论】:

    标签: ios json swift swift2 alamofire


    【解决方案1】:

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

    所以你有 self._id 的地方把它改成 self._id!

    【讨论】:

    • 我这样做了,debugPrint 现在给出了这个:[“users”:[[“_id”:“1234567”],[“_id”:“665543”]]]。但不幸的是,我仍然遇到同样的错误。
    • 好的,所以你发送了一个数组,它说 JSON 写入中的类型无效,所以它可能期待 JSON。您是否尝试过类似的方法: let json_data = NSJSONSerialization.dataWithJSONObject(users, options: nil, error: nil) ?
    • 那行给我一个错误“调用中的额外参数'错误'”
    • 不确定错误是否需要TBH。我目瞪口呆。我知道当使用 Alamofire 提取 JSON 时,您将只使用选项。尝试消除它,以便您的论点只是用户和选项:nil
    猜你喜欢
    • 2020-04-03
    • 2017-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-12
    相关资源
    最近更新 更多