Swift 2 parse Json as Optional for an array

I get a 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, the list looks like this (it ends in this part of 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; } )) 

Now I have to convert this json object to an array (or NSDictionary) and skip it. Can anyone advise how?

+4
ios swift swift2
Nov 03 '15 at 21:13
source share
2 answers

Currently, you cannot scroll your object because it was listed as AnyObject your code. Using your current code, are you sending JSON or as? NSDictionary as? NSDictionary , or as? AnyObject as? AnyObject .

But since JSON always starts with a dictionary or 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 NSDictionary and NSArray, but that is up to you.

+4
Nov 03 '15 at 23:05
source share

try it

 let jsonDictionary = try NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers) as? [String:AnyObject] 
0
Nov 03 '15 at 21:39
source share



All Articles