我正在从网络服务获取国家/地区列表。收到后我用这段代码来处理它:
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 以某种方式)并循环遍历它。有人可以建议如何吗?
目前您无法循环遍历您的对象,因为它已被转换为AnyObject
通过你的代码。使用当前代码,您可以转换 JSON 数据as? NSDictionary
or 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,但这取决于您。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)