Reputation: 8714
I am getting list of countries from a web service. After receiving it I used this code to process it:
if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {
// triggering callback function that should be processed in the call
// doing logic
} else {
if let json = try NSJSONSerialization.JSONObjectWithData(data!, options:[]) as? AnyObject {
completion(json)
} else {
let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("Error could not parse JSON string: \(jsonStr)")
}
}
And after that list looks like this (it ends up in this part NSJSONSerialization.JSONObjectWithData(data!, options:[]) as? AnyObject
) :
Optional((
{
"country_code" = AF;
"dial_code" = 93;
id = 1;
name = Afghanistan;
},
{
"country_code" = DZ;
"dial_code" = 213;
id = 3;
name = Algeria;
},
{
"country_code" = AD;
"dial_code" = 376;
id = 4;
name = Andorra;
}
))
I should now convert this json object to array (or NSDictionary somehow) and to loop through it. Can someone advice how?
Upvotes: 4
Views: 1637
Reputation: 70109
Currently you can't loop through your object because it has been cast as AnyObject
by your code. With your current code you're casting the JSON data either as? NSDictionary
or as? AnyObject
.
But since JSON always start with a dictionary or an array, you should do this instead (keeping your example):
if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {
// process "json" as a dictionary
} else if let json = try NSJSONSerialization.JSONObjectWithData(data!, options:[]) as? NSArray {
// process "json" as an array
} else {
let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("Error could not parse JSON string: \(jsonStr)")
}
And ideally you would use Swift dictionaries and arrays instead of Foundation's NSDictionary and NSArray, but that is up to you.
Upvotes: 4
Reputation: 1000
try this
let jsonDictionary = try NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers) as? [String:AnyObject]
Upvotes: 0