我正在尝试使用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 \“}”包括所有引号,所以格式对我来说看起来不太正确,可能是前导和尾随双引号正在抛弃它?
错误很明显。结果是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)
}
}
}