迅捷的json:对象数组

时间:2014-12-13 01:12:03

标签: json url swift

我正在尝试将json对象数组转换为Dictionary,

我有这段代码:

func load() { //this function is the first that is executed

    getActivities {
        (response) in
        self.loadActivities(response as NSArray)
    }
}

func getActivities(callback:(NSDictionary) -> ()){ //the next url contains the json array of objects
    request("http://localhost/llancaActivity/public/activity/getListJSON/0/2", callback: callback)
}

func request(url:String, callback:(NSDictionary) -> ()){
    var nsURL : NSURL = NSURL(string: url)!;

    let task = NSURLSession.sharedSession().dataTaskWithURL(nsURL){
        (data, response, error) in
        var error: NSError?
        var response = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &error) as NSDictionary;

        callback(response);
    }

    task.resume();
}


func loadActivities(activities:NSArray){
    for activity in activities {
        println(activity["id"]); //<-- These line never is executed!!!! 
    }
}

如果我使用浏览器访问下一个URL:http:// localhost / llancaActivity / public / activity / getListJSON / 0/2

我有下一个回复:

 [{"id":"3","title":"Confer\u00e8ncia de meteorologia \u201cEl canvi clim\u00e0tic\u201d","description":"Hora: 19h\nLloc: Sala de Confer\u00e8ncies de la Casa de Cultura","start_date":"2014-12-13","end_date":"2014-12-13","id_category":null},{"id":"4","title":"Espectacle a favor de la Marat\u00f3 de TV3","description":"Hora: 17h\nEntrada: la voluntat\nLloc: Sala d\u2019Actes de la Casa de Cultura\nOrganitza: Associaci\u00f3 de Puntaires de Llan\u00e7\u00e0\nCol\u00b7labora: Entitats i Associacions de Llan\u00e7\u00e0 i l\u2019Ajuntament de Llan\u00e7\u00e0","start_date":"2014-12-13","end_date":"2014-12-13","id_category":null}]

对不起我的英语......

2 个答案:

答案 0 :(得分:1)

您正在尝试返回JSON的字典表示,但它不是字典。这是一个阵列。是的,这是一系列字典,但这与简单的字典完全不同。

所以JSON解析就是:

let responseObject = NSJSONSerialization.JSONObjectWithData(data!, options: nil, error: &parseError) as NSArray

将其整合到您的request函数中,它看起来像:

func request(urlString: String, callback: (responseObject: NSArray?, error: NSError?) -> ()) {
    let url = NSURL(string: urlString)!

    let task = NSURLSession.sharedSession().dataTaskWithURL(url) {
        data, response, error in

        if data == nil {
            callback(responseObject: nil, error: error)
        } else {
            var parseError: NSError?
            let responseObject = NSJSONSerialization.JSONObjectWithData(data!, options: nil, error: &parseError) as? NSArray
            callback(responseObject: responseObject, error: parseError)
        }
    }
    task.resume()
}

注意:

  • 我更改了闭包以返回两个参数responseObjecterror(调用者可以检测到错误),但这取决于您。

  • 我将NSJSONSerialization结果投放到NSArray,而不是NSDictionary

  • 更准确地说,我实际上将它转换为可选数组(使用as?),因此它可以优雅地处理任何解析错误。

或者,你可以让它返回Swift字典的Swift数组:

func request(urlString: String, callback: (responseObject: [[String: AnyObject]]?, error: NSError?) -> ()) {
    let url = NSURL(string: urlString)!

    let task = NSURLSession.sharedSession().dataTaskWithURL(url) {
        data, response, error in

        if data == nil {
            callback(responseObject: nil, error: error)
        } else {
            var parseError: NSError?
            let responseObject = NSJSONSerialization.JSONObjectWithData(data!, options: nil, error: &parseError) as? [[String: AnyObject]]
            callback(responseObject: responseObject, error: parseError)
        }
    }
    task.resume()
}

显然,无论你将request封闭更改为什么,你都希望对getActivities进行相同的更改,但这应该是自我解释的。

答案 1 :(得分:0)

使用swifty,您只需要发出以下节来将json数组的dicts转换为对象:

let data = "[{\"id\":\"3\",\"title\":\"Confer\u00e8ncia de meteorologia \u201cEl canvi clim\u00e0tic\u201d\",\"description\":\"Hora: 19h\nLloc: Sala de Confer\u00e8ncies de la Casa de Cultura\",\"start_date\":\"2014-12-13\",\"end_date\":"2014-12-13\",\"id_category\":null}" // .... and the rest of your JSON
let json = JSON(data:data)

现在json将拥有已解析的数据。