【问题标题】:Alamofire request with SwiftyJSON parameters带有 SwiftyJSON 参数的 Alamofire 请求
【发布时间】:2017-12-15 19:50:59
【问题描述】:

我想知道如何将 SwiftyJSON 数组放入我的 Alamofire 请求参数中。

实际上我使用这段代码(Swift 3)来设置请求的参数:

让 params = ["customObjects": customObjects.map({$0.toJSON()})]

...但是如果我尝试启动请求,这会引发异常:

未捕获的异常 'NSInvalidArgumentException',原因:'JSON 写入 (_SwiftValue) 中的类型无效'

“customObjects”是我的自定义模型类的数组。

如果您需要更多信息,请告诉我。

【问题讨论】:

  • "..但这会引发异常"什么异常?
  • 我编辑了我的问题
  • toJSON() 到底是做什么的?它只返回 Dictionary、Array、String 和 Int 吗?
  • 它返回一个 JSON(来自 SwiftyJSON),例如:let json: JSON = ["key": "value"]。里面的所有值都是 String 或 Int
  • 您能检查一下let jsonData = try JSONSerialization.data(withJSONObject: params, options: []) 是否有效吗?如果没有,let jsonData2 = try JSONSerialization.data(withJSONObject: customObjects.map({$0.toJSON(), options: [])

标签: ios swift alamofire swifty-json


【解决方案1】:

我自己找到了解决办法:

let params = ["customObjects": customObjects.map({$0.toDictionary()})]

这里是我的 CustomObject 中的 toDictionary() 函数:

func toDictionary() -> [String: Any] {
    let dict: [String: Any] = [
        "exampleKey": "exampleValue",
        "exampleKey2": "exampleValue2"
    ]

    return dict
}

我猜这是因为您可以使用 encoding: JSONEncoding.default 设置 Alamofire。

【讨论】:

    【解决方案2】:

    您可以将 SwiftyJSON 对象(此处称为 yourJSON)转换为如下参数:

    let parameters : Parameters = yourJSON.dictionaryObject ?? [:]
    

    然后你可以像这样在 Alamofire 请求中使用它:

    Alamofire.request("https://yourURL.com/somePath", method: .post, parameters: parameters, encoding:  JSONEncoding.default, headers: nil).responseJSON { response in
       // ... do whatever you would like with the response 
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-07
      • 1970-01-01
      • 2015-05-09
      相关资源
      最近更新 更多