gpt4 book ai didi

arrays - 将 JSON 解析为 swift 预定义数组

转载 作者:行者123 更新时间:2023-11-28 06:50:45 24 4
gpt4 key购买 nike

我正在尝试从 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)
}

我收到以下错误:

Could not cast value of type '_NSInlineData' (0x1a0cfd428) to 'NSDictionary' (0x1a0cf3380).

编辑:这里抛出错误:

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

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

最佳答案

您好,您的数据变量不包含您要查找的 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:如果您需要更多帮助,请告诉我。

关于arrays - 将 JSON 解析为 swift 预定义数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34980519/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com