Alamofire无法将NSCFString类型转换为字典

时间:2019-03-21 12:20:48

标签: json xcode swift4 alamofire

我正在尝试使用Alamofire从Web服务获得响应。 该服务返回的是JSON格式的字符串,但出现错误:“无法将NSCFString类型的值转换为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!"
                }
        }

当我打印响应时,我得到-成功:{“ SoNumber”:“ SO-1234567”}

当我使用Postman测试URL时,结果为:“ {\” soNumber \“:\” SO-1234567 \“}}”包括所有引号,因此该格式在我看来不太正确,也许前导和尾随双引号使它丢掉了?

1 个答案:

答案 0 :(得分:0)

错误已清除。结果是一个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)
            }
    }
}