我正在尝试为iPhone开发一个应用程序,该应用程序应使用nodejs + MongoDB编写的Web服务。该应用程序是用Swift制作的,但是现在我遇到了一个问题,我没有正确地解析数据。
目前,我有这样的代码:
var endpoint = NSURL(string: self.url + "?latitud=" + self.latitude + "&longitud=" + self.longitude)
var data = NSData(contentsOfURL: endpoint!)
var error: NSError? = nil
if let json: NSDictionary = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers, error: &error) as? NSDictionary {
for place in json {
var name = place["obj"]["name"]
var coords = place["obj"]["coords"]
var annotation = MKPointAnnotation()
annotation.title = name as? String
annotation.coordinate = coords as? CLLocationCoordinate2D
map.addAnnotation(annotation)
}
}
不幸的是,它不起作用:(
Web服务的响应与此类似:
[
{
"dis": 1.22,
"obj": {
"name": "Some name",
"coords": [
-97.1228,
17.4049
],
"phones": [
"555 555 55555",
"444 444 44444"
],
"address": {
"street": "Some Street",
"zip": "00000"
}
}
},
{
"dis": 2.03,
"obj": {
"name": "Othe name",
"coords": [
-97.0910
17.7099
],
"phones": [
"777 777 7777"
],
"address": {
"street": "Other street",
"zip": "11111"
}
}
}
]
那就是我做错了吗?
有没有更优雅(特别有效)的方法来向RESTful API发出请求?
最佳答案
您的其余API将返回NSDictionary数组,如果您替换if let json: NSDictionary = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers, error: &error) as? NSDictionary {
与if let boardsDictionary = NSJSONSerialization.JSONObjectWithData(inputData, options: NSJSONReadingOptions.MutableContainers, error: &error) as? Array<NSDictionary> {
您应该以数组形式获取数据。这将使您访问数据
关于ios - 解析JSON以进行iOS定位,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28940719/