Swift 2将Jsonparsing为数组的可选项

我从Web服务获取国家列表。 收到它后,我用这个代码来处理它:

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)") } } 

在这个列表看起来像这样(它在这个部分结束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; } )) 

我现在应该将这个json对象转换为数组(或者某种程度上是NSDictionary)并循环。 有人可以build议如何?

目前你不能遍历你的对象,因为它被代码转换为AnyObject 。 用您当前的代码,您正在投射JSON数据as? NSDictionary as? NSDictionaryas? AnyObject as? AnyObject

但是由于JSON总是以字典或数组开头,所以应该这样做(保持您的示例):

 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)") } 

理想情况下,您将使用Swift字典和数组而不是Foundation的NSDictionary和NSArray,但这取决于您。

尝试这个

 let jsonDictionary = try NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers) as? [String:AnyObject]