【问题标题】:I cannot compile my alamofire code due to ambiguous reference to member jsonObject. Why?由于对成员 jsonObject 的不明确引用,我无法编译我的 alamofire 代码。为什么?
【发布时间】:2017-03-17 00:57:11
【问题描述】:

我在Swift 中有一个代码,我通过Alamofire 调用我的后端代码:

Alamofire.request(url, method: .post, parameters: (parameters), encoding: JSONEncoding.default)
  .validate()
  .responseJSON { response in
      switch response.result {
      case .success:
             do {
             if let jsonData = try JSONSerialization.jsonObject(with: response.result.value, options:.allowFragments) as? [String:Any] {
              for requestJSON in jsonData["geojson"]["features"] {
                  if let request = SingleCluster.fromJSON(JSON(requestJSON)){
                      let pinOne = CustomCluster()
                      pinOne.coordinate = CLLocationCoordinate2D(latitude: request.latitude, longitude: request.longitude)
                      pinOne.amount = request.amount

                      self.eventsArray.append(pinOne);
                  }
              }
          }
             } catch let err{
              print(err.localizedDescription)
             }

          completionHandler!()

      case .failure(let error):
          print("error")
      }

}

问题在于这一行:

 if let jsonData = try JSONSerialization.jsonObject(with: response.result.value, options:.allowFragments) as? [String:Any] {

带来一个错误:

Ambiguous reference to member 'jsonObject(with:options:)'

我尝试将其转换为 [String:Any][String:AnyObject] 但它没有改变任何东西。我在这里做错了什么?

【问题讨论】:

标签: json swift swift3 alamofire swifty-json


【解决方案1】:

你已经使用responseJSONAlamofire,所以你会在完成块中得到序列化的JSON,不需要使用JSONSerialization直接使用它。

switch response.result {
case .success:
     if let jsonData = JSON(response.result.value) {
         for requestJSON in jsonData["geojson"]["features"] {
              if let request = SingleCluster.fromJSON(requestJSON){
                  let pinOne = CustomCluster()
                  pinOne.coordinate = CLLocationCoordinate2D(latitude: request.latitude, longitude: request.longitude)
                  pinOne.amount = request.amount
                  self.eventsArray.append(pinOne);
              }
          }
     }
case .failure(let error):
      print("error")
}

【讨论】:

    【解决方案2】:

    改变这一行:

    if let jsonData = try JSONSerialization.jsonObject(with: response.result.value, options:.allowFragments) as? [String:Any] {
    

    收件人:

    if let data = response.data, let jsonData = try JSONSerialization.jsonObject(with: data, options:.allowFragments) as? [String:Any] {
    

    【讨论】:

      猜你喜欢
      • 2022-01-12
      • 2023-03-29
      • 2013-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-03
      • 1970-01-01
      相关资源
      最近更新 更多