【问题标题】:Alamofire could not cast type of NSCFString to dictionaryAlamofire 无法将 NSCFString 类型转换为字典
【发布时间】:2019-03-21 12:20:47
【问题描述】:

我正在尝试使用 Alamofire 从网络服务获取响应。 该服务正在返回 JSON 格式的字符串,但我收到错误消息:'Could not cast value of type NSCFString to NSDictionary'

我的代码是:

func getSoFromMo() {
        let apiUrl: String = "http://xxxxxxxxxxxxxxx"

        Alamofire.request(apiUrl)
            .responseJSON{ response in
                print(response)

                if let resultJSON = response.result.value {
                    let resultObj: Dictionary = resultJSON as! Dictionary<String, Any>  <==== Breaks on this line
                    self.soNum = resultObj["soNumber"] as! String
                    self.lblValidate.text = "\(self.soNum)"
                    } else {
                    self.soNum = "not found!"
                }
        }

当我打印得到的响应时 - SUCCESS: {"SoNumber": "SO-1234567"}

当我使用 Postman 测试 URL 时,结果是: "{\"soNumber\": \"SO-1234567\"}" 包括所有引号,所以格式对我来说看起来不太正确,也许是前导和尾随双引号将其丢弃?

【问题讨论】:

  • 错误清楚地表明value 不是字典。但是 JSON 中的 JSON 非常不寻常。请将print(response) 替换为print(String(data: response.data!, encoding: .utf8)!) 并添加结果。
  • 这里是打印结果:"{\"soNumber\": \"SO-1234567\"}"

标签: json xcode swift4 alamofire


【解决方案1】:

错误很明显。结果是 JSON 字符串而不是反序列化的字典。

你必须添加一行来反序列化字符串

func getSoFromMo() {
    let apiUrl: String = "http://xxxxxxxxxxxxxxx"

    Alamofire.request(apiUrl)
        .responseJSON { response in
            print(response)
            do {
                if let data = response.data, 
                   let resultObj = try JSONSerialization.jsonObject(with: data) as? [String:Any] {
                      self.soNum = resultObj["soNumber"] as! String
                      self.lblValidate.text = self.soNum // no String Interpolation, soNum IS a string
                } else {
                    self.soNum = "not found!"
                }
            } catch {
               print(error)
            }
    }
}

【讨论】:

  • 谢谢,我试了一下,现在得到一个不同的错误:“JSON 文本没有以数组或对象开头,并且允许未设置片段的选项”听起来我需要允许该选项,如何我应该这样做吗?
  • 对于给定的输出,这个错误一定不会发生。你真的使用我的代码吗?例如`response.data'
  • 所以,我找到了允许片段选项,不再出现该错误,但现在它进入“else”块并显示“未找到”
  • 如果 printout 正是您在问题下方评论中的值,即使没有选项,我的代码也必须工作。
  • 仔细检查,我使用的是您的确切代码,返回的数据是 "{\"soNumber\": \"SO-1234567\"}"
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-26
  • 1970-01-01
  • 2018-08-17
  • 2014-03-30
  • 2012-03-01
相关资源
最近更新 更多