解析JSON数组

时间:2015-07-19 13:36:35

标签: json swift parsing

我正在开发一种从我的应用程序中解析网络中的json的方法。

来源:http://api.randomuser.me/

我的代码:

var bytes: NSMutableData?

@IBAction func loadJson(sender: AnyObject) {

    let request = NSURLRequest(URL: NSURL(string: "http://api.randomuser.me/")!)

    let loader = NSURLConnection(request: request, delegate: self, startImmediately: true)

}

func connection(didReceiveResponse: NSURLConnection!, didReceiveResponse response: NSURLResponse!) {

        self.bytes = NSMutableData()

}

func connection(connection: NSURLConnection!, didReceiveData conData: NSData!) {

        self.bytes?.appendData(conData)

}

func connectionDidFinishLoading(connection: NSURLConnection!) {

    let jsonResult: Dictionary = NSJSONSerialization.JSONObjectWithData(self.bytes!, options: NSJSONReadingOptions.MutableContainers, error: nil) as! Dictionary<String, AnyObject>

    let results: NSArray = jsonResult["results"]! as! NSArray

    println(results)

    for result in results {

        // Works
        println(result)

        // Works
        println(result["seed"])

        // Does not work !!! why?
        println(result["user"]["email"])

    }

}

为什么我无法从阵列收到电子邮件?

如果您愿意,可以查看上面链接中的json。

1 个答案:

答案 0 :(得分:1)

通过使用SwiftyJSON,您可以通过以下方式轻松处理JSON数据:

@IBAction func loadJson(sender: AnyObject) {

    let baseURL = NSURL(string: "http://api.randomuser.me/")
    let userData = NSData(contentsOfURL: baseURL!)

    let json = JSON(data: userData!)
    let seeds = json["results"][0]["seed"].stringValue
    let email = json["results"][0]["user"]["email"].stringValue
    println(seeds)    //1bbefb89fc47c81501
    println(email)    //luz.hidalgo44@example.com
}

希望这会有所帮助。