John Mims
John Mims

Reputation: 53

Getting data from an array in JSON data with Swift

I'm converting zip code data to city and state using http://api.zippopotam.us. I'm able to pull out the country easily, but the "place name" (city) and "state abbreviation" are giving me problems. Here's the code:

var url = NSURL(string: "http://api.zippopotam.us/us/90210")

let task = NSURLSession.sharedSession().dataTaskWithURL(url!, completionHandler: {(data, response, error) -> Void in

let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSDictionary

        var placeDictionary = jsonResult["places"]! as? NSArray

        println(placeDictionary) // this works

        var name: String? = jsonResult[0]!.valueForKey("place name") as? String

        println(name) // this doesn't. 

})

task.resume()

I'm getting an error:

Unexpectedly found nil while unwrapping an Optional value

Upvotes: 2

Views: 881

Answers (2)

Lars Christoffersen
Lars Christoffersen

Reputation: 1739

If you are using JSON a lot, SwiftyJSON is worth checking out. It simplifies dealing with JSON a lot, since apple has not given us a good JSON API.

Upvotes: 1

AstroCB
AstroCB

Reputation: 12367

Look at the cleaned up JSON:

{
   "post code":"90210",
   "country":"United States",
   "country abbreviation":"US",
   "places":[
      {
         "place name":"Beverly Hills",
         "longitude":"-118.4065",
         "state":"California",
         "state abbreviation":"CA",
         "latitude":"34.0901"
      }
   ]
}

The array is not directly in the JSON; to get there, you have to access the places key.

You've done that with placeDictionary (which should really be placeArray). Since you've saved that array, you can access elements of it (which are dictionaries) and their respective dictionaries.

So, to get the first place name, you'd use this:

if let placeName: String = (placeDictionary[0] as! NSDictionary).valueForKey("place name") as? String {
    println(placeName)
}

Upvotes: 3

Related Questions