Swift函数解析JSON并返回一个字典数组

时间:2016-07-31 11:05:49

标签: json swift alamofire swifty-json

我试着编写一个解析JSON的函数。函数的返回值是字典array。不幸的是,我遇到的问题是作业result = data as! [[String:AnyObject]]不起作用。 print(data)返回我的JSON很棒,但print(result)只给我一个空数组。令人惊讶的是方法print(result) 首先运行,然后运行方法print(data)

我试过的代码:

import Foundation
import Alamofire
import SwiftyJSON

func getPlayers() -> Array<Dictionary<String, AnyObject>>  {

    var result = [[String:AnyObject]]()

    Alamofire.request(.GET, "http://example.com/api/v1/players", parameters: ["published": "false"])
        .responseJSON { (responseData) -> Void in
            if((responseData.result.value) != nil) {
                let response = JSON(responseData.result.value!)

                if let data = response["data"].arrayObject {
                    print(data)
                    result = data as! [[String:AnyObject]]
                }
            }
    }

    print(result)

    return result
}

1 个答案:

答案 0 :(得分:4)

Api以async(后台)方式调用工作,这就是您需要使用swift closure而不是返回dictionary的原因。像这样改变你的代码

func getPlayers(completion: (Array<Dictionary<String, AnyObject>>) -> ()))  {

    var result = [[String:AnyObject]]()

    Alamofire.request(.GET, "http://example.com/api/v1/players", parameters: ["published": "false"])
        .responseJSON { (responseData) -> Void in
            if((responseData.result.value) != nil) {
                let response = JSON(responseData.result.value!)
                if let data = response["data"].arrayObject {
                    print(data)
                    result = data as! [[String:AnyObject]]
                }
            }
            completion(result)
     }
}

并像这样打电话

self.getPlayers() { (result) -> () in
     print(result)
}