Swift 2将Json解析为可选的数组

时间:2015-11-03 21:13:18

标签: ios swift swift2

我从网络服务获取国家/地区列表。收到后我用这个代码来处理它:

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)并循环遍历它。有人可以建议吗?

2 个答案:

答案 0 :(得分:4)

目前,您无法循环访问您的对象,因为您的代码已将其转换为AnyObject。使用您当前的代码,您可以{J}数据as? NSDictionaryas? 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,但这取决于你。

答案 1 :(得分:0)

试试这个

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