user616076 user616076 - 2 months ago 6
Swift Question

How can I access my JSON object?

I'm getting a JSON object returned from a URL request and I've converted it using the code below

let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
if error != nil {
self.alertView("Error - " + error!.localizedDescription)
}
else {
do {
if let json = try NSJSONSerialization.JSONObjectWithData(data!, options:.AllowFragments) as? Dictionary<String, AnyObject> {
for item in json {
if (item as? (String, AnyObject)) != nil {
//Get values here


This works but the value of item is displayed below. I've tried several methods but I can't get the values for the Dictionary with 23 key/value pairs.

enter image description here

The variable item is declared as (String, AnyObject). How can I retreive these values?

Answer

The Dictionary with 23 key/value pairs is the value for key result

if let json = try NSJSONSerialization.JSONObjectWithData(data!, options:.AllowFragments) as? Dictionary<String, AnyObject> {
   if let result = json["result"] as? [String:AnyObject] {
      for (key, value) in result {
          print(key, value)
      }
   } 
}