我正在从Web服务获取国家/地区列表.收到它后,我使用以下代码对其进行处理:
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)") } }然后该列表看起来像这样(它在此部分NSJSONSerialization.JSONObjectWithData(data!, options:[]) as? AnyObject中结束):
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; } ))我现在应该将此json对象转换为数组(或以某种方式转换为NSDictionary)并遍历它.有人可以建议吗?
I should now convert this json object to array (or NSDictionary somehow) and to loop through it. Can someone advice how?
推荐答案当前,您无法遍历对象,因为该对象已被您的代码强制转换为AnyObject.使用当前代码,您正在投射as? NSDictionary或as? AnyObject的JSON数据.
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.
但是由于JSON总是以字典或数组开头,因此您应该这样做(保留示例):
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)") }理想情况下,您将使用Swift词典和数组而不是Foundation的NSDictionary和NSArray,但这取决于您.
And ideally you would use Swift dictionaries and arrays instead of Foundation's NSDictionary and NSArray, but that is up to you.
更多推荐
Swift 2将Json解析为可选数组
发布评论