Chaim Friedman Chaim Friedman - 5 months ago 10
Swift Question

JSONObjectWithData failing in Swift

I am using REST api's (from HERE maps) for various services. I am trying to parse JSON results. One works and the other doesn't.

The first one is a direction service that will spit out a direction between 2 locations. This is the JSON output:

{"results":[{"waypoints":[{"id":"1 Infinite Loop","lat":37.331998,"lng":-122.03078,"sequence":0,"estimatedArrival":null,"estimatedDeparture":"2016-10-19T09:30:00+01:00","fulfilledConstraints":[]},{"id":"Cypress Drive","lat":37.330196,"lng":-122.021369,"sequence":1,"estimatedArrival":null,"estimatedDeparture":null,"fulfilledConstraints":[]}],"distance":"2589","time":"314","interconnections":[{"fromWaypoint":"1 Infinite Loop","toWaypoint":"Cypress Drive","distance":2589.0,"time":314.0,"rest":0.0,"waiting":0.0}],"description":"Targeted best time; with , improvement for traffic","timeBreakdown":{"driving":314,"service":0,"rest":0,"waiting":0}}],"errors":[],"processingTimeDesc":"139ms","responseCode":"200","warnings":null,"requestId":null}


The next one is a different API with an even simpler request, it will geocode a postal address. This is the JSON output:

{"results":{"MetaInfo":{"Timestamp":"2016-06-23T17:24:00.003+0000"},"View":[{"_type":"SearchResultsViewType","ViewId":0,"Result":[{"Relevance":0.89,"MatchLevel":"houseNumber","MatchQuality":{"State":1.0,"City":0.89,"Street":[0.87],"HouseNumber":1.0},"MatchType":"pointAddress","Location":{"LocationId":"NT_XJ6VcnP0-isqXdG1YBq.vA_xA","LocationType":"address","DisplayPosition":{"Latitude":37.33177,"Longitude":-122.03042},"NavigationPosition":[{"Latitude":37.33178,"Longitude":-122.03079}],"MapView":{"TopLeft":{"Latitude":37.3328942,"Longitude":-122.0318338},"BottomRight":{"Latitude":37.3306458,"Longitude":-122.0290062}},"Address":{"Label":"1 Infinite Loop, Cupertino, CA 95014, United States","Country":"USA","State":"CA","County":"Santa Clara","City":"Cupertino","Street":"Infinite Loop","HouseNumber":"1","PostalCode":"95014","AdditionalData":[{"value":"United States","key":"CountryName"},{"value":"California","key":"StateName"},{"value":"Santa Clara","key":"CountyName"},{"value":"N","key":"PostalCodeType"}]}}}]}]}}


My code to parse the JSON in swift works beautifully on the first one:

if let url = NSURL(string: therl),

JSONData = NSData(contentsOfURL: url),
json = try? NSJSONSerialization.JSONObjectWithData(JSONData, options: []),
dict = json as? [String: AnyObject],

results = dict["results"] as? [[String: AnyObject]] {
for result in results {
print (result)
}
} else {
print("unable to connect!")
}


But fails on the second one!!

Answer

At the second one the results is not an Array, it's a Dictionary

Edited to show how to recover the first Latitude value

Following with your code...

if let 
    url = NSURL(string: therl),
    JSONData = NSData(contentsOfURL: url),
    json = try? NSJSONSerialization.JSONObjectWithData(JSONData, options: []),
    dict = json as? [String: AnyObject],
    results = dict["results"] as? [String: AnyObject],
    views = results["View"] as? [[String: AnyObject]]
    {
        for view in views
        {
            if let resultNodes = views["Result"] as? [[String: AnyObject]]
            {
                for resultNode in resultNodes
                {
                    if let location = resultNode["Location"] as? [String: AnyObject]
                    {
                        if let address = location["Address"] as? [String: AnyObject]
                        {
                            // Process the address dictionary...
                        }

                        if let displayPosition = location["DisplayPosition"] as? [String: AnyObject]
                        {
                            // Process the Display Position dictionary...
                            let latitude: Double = displayPosition["Latitude"] as! Double
                            let longitude: Double = displayPosition["Longitude"] as! Double
                        }

                        // ... other values...
                    }
                }
            }
        } 
    }