将JSON解析为快速预定义数组

时间:2016-01-24 19:38:39

标签: arrays json swift parsing

我正在尝试从api(JSON)获取项目并将其解析为预定义的swift数组。我已经搜索并查找了几个小时,但由于我缺乏技能,我无法找到适合我的情况。

我的预定义数组如下所示:

init?(participants: String, photoguest: UIImage?, photohome: UIImage?, time: String, stadium: String, channel: String)

JSON结构是这样的(entire json file):

{"gameId":"255","gameWeek":"17","gameDate":"2016-01-03","awayTeam":"SEA","homeTeam":"ARI","gameTimeET":"4:25 PM","tvStation":"FOX","winner":"SEA"}

我当前的代码如下所示(Games是我从表格单元格中连接变量的类):

var gameplan = [Games]()

func loadNFLgames(){

    let apiURL = NSURL(string: "http://www.fantasyfootballnerd.com/service/schedule/json/test/")
    let data: AnyObject? = NSData(contentsOfURL: apiURL!)


    let homeTeam = (data as! NSDictionary)["homeTeam"] as! String
    let awayTeam = (data as! NSDictionary)["awayTeam"] as! String
    let gameDate = (data as! NSDictionary)["gameDate"] as! String
    let gameTimeET = (data as! NSDictionary)["gameTimeET"] as! String
    let tvStation = (data as! NSDictionary)["tvStation"] as! String

    /*
    for schleife mit API daten:
        for gameWeek = currentWeek{ //every game where gameWeek matches currentWeek
    */

    // create variables from api calls
    let api_guest = awayTeam
    let api_home = homeTeam
    let api_tvhost = tvStation
    let api_time = gameDate + ", " + gameTimeET + " ET" // convert gameDate to day e.g. SUN
    let api_stadion = "N/A"

    // prepare data for array
    let gamedata = Games(participants: api_guest+" @ "+api_home, photoguest: UIImage(named: api_guest), photohome: UIImage(named: api_home), time: api_time, stadium: api_stadion, channel: api_tvhost)!

    // add data to array
    gameplan.append(gamedata)
}

我收到以下错误:

  

无法将类型'_NSInlineData'(0x1a0cfd428)的值转换为   'NSDictionary'(0x1a0cf3380)。

编辑:错误在这里抛出:

let homeTeam = (data as! NSDictionary)["homeTeam"] as! String

非常感谢您的帮助。 提前谢谢!

2 个答案:

答案 0 :(得分:1)

你好你的数据变量不包含你要找的Json。所以你必须像亚历山大建议的那样将它序列化为json,但NSJSONSerialization会抛出一个错误,所以我们在try中输入了 所以你的代码将是这样的(我建议总是使用dispatch_async在后台线程中使用它而不是使用完成闭包来获得结果) - >

    func loadNFLgames(completionClosure: (result : [Games]) ->()){
        let queue: dispatch_queue_t = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
        dispatch_async(queue, {
            let URL = "http://www.fantasyfootballnerd.com/service/schedule/json/test/"
            print(URL)
            if let data = NSData(contentsOfURL: NSURL(string: URL)!){
                if let JsonObject = try? NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as! NSMutableDictionary{
                    print(JsonObject)
                    //here you can loop through the JsonObject to get the data you are looking for
                    //when you get your array of Games just pass it the the completion closure like this
completionClosure(result: gameplan)
                }
            }

        })
    }

PS:如果您需要更多帮助,请与我们联系。

答案 1 :(得分:0)

您的let decodedJson = NSJSONSerialization.JSONObjectWithData(data, options: nil) as! NSDictionary变量是NSData类型(不是NSDictionary)。你必须转换它才能使用它。尝试类似的东西:

let homeTeam = decodedJson["homeTeam"] as! String

而且你可以像标准词典一样使用它

{{1}}