【发布时间】: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