在Swift中访问JSON对象时出错

时间:2014-06-11 16:58:28

标签: ios json swift

我有这个Swift代码:

func getData(completion: (array: Array<AnyObject>)->Void) {
    UIApplication.sharedApplication().networkActivityIndicatorVisible = true

    let session: NSURLSession = NSURLSession(configuration: sessionConfiguration)
    var request: NSURLRequest = NSURLRequest(URL: NSURL(string: "http://coinabul.com/api.php"))

    let task: NSURLSessionDataTask = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
        if !error {
            let httpResp: NSHTTPURLResponse = response as NSHTTPURLResponse
            if httpResp.statusCode == 200 {
                var json: NSDictionary = self.convertDataToJSON(data)
                var myArray: Array = Array<Currency>()

                for (key: AnyObject, object: AnyObject) in json {
                    let info: NSDictionary = object as NSDictionary

                    let grams: CGFloat = info["Grams"] as CGFloat
                    let ounces: CGFloat = info["Ounces"] as CGFloat
                    let usd: CGFloat = info["USD"] as CGFloat

                    // Do something with those values
                }
            }
        }
        })

    task.resume()
}

func convertDataToJSON(data: NSData) -> NSDictionary {
    var error: NSError?
    var jsonDictionary: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers, error: &error) as NSDictionary

    return jsonDictionary
}

&#34; json&#34; NSDictionary是正确的。如果我打印它:

{
    BTC =     {
        Grams = "15.398340412292";
        Ounces = "0.49506814017307";
        SilverGrams = "1010.0959168583";
        SilverOunces = "32.475337832916";
        USD = "624.825500000000";
    };
    Gold =     {
        Grams = "0.06494206341493";
        Ounces = "2.0199239627704";
        USD = "1262.100000000000";
    };
    Silver =     {
        Grams = "0.0009900049917623401";
        Ounces = "0.030792597293164";
        USD = "19.240000000000";
    };
}

我可以json["Silver"]获取相应的对象。但如果我尝试json["Silver"]["USD"]我的应用程序崩溃了。

我在这里缺少什么?

1 个答案:

答案 0 :(得分:1)

表达式:

json["Silver"]

返回不允许[]的AnyObject?,因为它不知道它是什么,所以你必须对其进行类型转换以供进一步参考。请注意,如果您尝试在工作区中执行此操作,Xcode将会崩溃

json["Silver"] as? Dictionary

您可以使用可选链接将它们全部串在一起,如:

(json["Silver"] as? NSDictionary)?["USD"]

请注意,索引操作的结果几乎总是选项,并且可选链接意味着这个选项肯定是可选的,因此您必须处理检查和解包。