Swift 2将Json解析为可选数组 [英] Swift 2 parse Json as Optional to array

查看:103
本文介绍了Swift 2将Json解析为可选数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从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? NSDictionaryas? 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解析为可选数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆