简体   繁体   English

Swift JSON for-in循环

[英]Swift JSON for-in loop

I am trying to loop trough a serie of items in a JSON object. 我试图循环通过一系列JSON对象中的项目。 However I run into some problems. 但是我遇到了一些问题。 My code compiles fine without errors but when it gets to the point where the JSON function triggers in stops emulating and gives an error. 我的代码可以正常编译,没有错误,但是到JSON函数触发停止仿真并给出错误的地步。

This is my code: 这是我的代码:

func getJSON() {
        let urlAsString = "http://localhost:8888/domainchecker/check.php?domain=/google.com"
        let url = NSURL(string: urlAsString)!
        let urlSession = NSURLSession.sharedSession()

        let jsonQuery = urlSession.dataTaskWithURL(url, completionHandler: { data, response, error -> Void in
            if (error != nil) {
                println(error.localizedDescription)
            }
            var err: NSError?

            var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as NSDictionary
            if (err != nil) {
                println("JSON Error \(err!.localizedDescription)")
            }

            let arrayFromJson: String! = jsonResult["ITEMS"] as NSString

            dispatch_async(dispatch_get_main_queue(), {
                for variable in arrayFromJson {
                    println("DOMAIN");
                }

            })
        })
        jsonQuery.resume()
    }

This is the JSON result: 这是JSON结果:

{ "ITEMS": [ { "DOMAIN": "google.nl", "AVAILABLE": "NO", "PRICE": "-" }{ "DOMAIN": "google.com", "AVAILABLE": "NO", "PRICE": "-" }{ "DOMAIN": "google.eu", "AVAILABLE": "NO", "PRICE": "-" } ] }

and this is the error we receive: 这是我们收到的错误:

fatal error: unexpectedly found nil while unwrapping an Optional value
(lldb)

I have been searching the web for a fix or alternatives, but to no avail. 我一直在网上搜索修复程序或替代方法,但无济于事。

Thanks in advance. 提前致谢。

在您的JSON结构中, jsonResult["ITEMS"]不是您声明的字符串,而是一个字典数组,因此您必须将其视为字典数组

let arrayFromJson: [[String:AnyObject]] = jsonResult["ITEMS"] as [[String:AnyObject]] 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM