0
votes

I have a NodeJS API that queries a MongoDB cluster and returns nearby data in the following format. The issue is I can't enumerate the locations with Swift 3 and XCode 8.1.

[ { "_id": "57b03fa32c6835946afd358c", "location": { "coordinates": [ 144.2, -34 ], "elevation": "1", "type": "Point" }, "name": "Resource 01", "url": "http://www.url.com/Resource01.html" }, { "_id": "34b03fa32c6835946afd358c", "location": { "coordinates": [ 154.2, -35.3 ], "elevation": "1", "type": "Point" }, "name": "Resource 02", "url": "http://www.url.com/Resource02.html" } ]

This is my Query code.

let json = try! JSONSerialization.jsonObject(with: data)

print(json)

if let statusesArray = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [[String: AnyObject]],
    let jsonbranch = statusesArray?[0] as? [String: AnyObject],
    let therecord = jsonbranch["_id"] as? String {
    print ("_id: " + therecord)
}

I tried to use SwiftyJSON but it does not work either?

1

1 Answers

0
votes

Solved:

if let jsonBranch = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [[String: AnyObject]],
    let name = jsonBranch?[0]["name"] as? String {
    print ("name: " + name)
}
if let jsonBranch = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [[String: AnyObject]],
    let name = jsonBranch?[1]["name"] as? String {
    print ("name: " + name)
}