【问题标题】:Parsing JSON into swift predefined array将 JSON 解析为快速的预定义数组
【发布时间】:2016-01-24 19:38:38
【问题描述】:

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

我当前的代码如下所示(游戏是我将数组中的变量与表格单元格项目连接起来的类):

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

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

【问题讨论】:

  • 嗯..有什么问题
  • 抱歉更新了帖子
  • 哪一行抛出了错误,或者我们猜想?
  • NSDictionary 错误正在抛出:let homeTeam = (data as! NSDictionary)["homeTeam"] as! String
  • 你需要解析 schedule 数组,然后循环每个 nsdictionary

标签: arrays json swift parsing


【解决方案1】:

您好,您的数据变量不包含您要查找的 Json。所以你必须像 alexander 建议的那样将它序列化为 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:如果您需要更多帮助,请告诉我。

【讨论】:

  • 谢谢,这似乎可以正常工作,但我收到警告:Cast from 'NSData' to unrelated type 'NSDictionary' always fails。最后没有显示单元格,但至少加载了表格。你知道解决办法吗?提前致谢
  • 没关系我修好了:)。抱歉,我刚开始使用 swift 进行开发。
  • 没问题。我很高兴它有帮助
  • 我仍然无法显示单元格,但至少我不再遇到错误了。
  • 你能粘贴你的代码吗?这会很有帮助。不要忘记在完成闭包中调用 tableView.reloadData()。
【解决方案2】:

您的 data 变量是 NSData 类型(不是 NSDictionary)。您必须对其进行转换才能使用它。试试这样的:

let decodedJson = NSJSONSerialization.JSONObjectWithData(data, options: nil) as! NSDictionary

你可以像标准字典一样使用它

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

【讨论】:

  • 我不能使用 nil 也不能使用 0 作为 NSReadoptions
  • options: [] 修复了它,但在 NSJSONSerialization call can throw but it is not marked with try 上出现另一个错误
  • 尝试以下操作:do { let decodedJson = try NSJSONSerialization.JSONObjectWithData(data, options: nil) as! NSDictionary } catch error { // error handle } 或者,如果您 100% 确定,该转换将没有任何错误,您可以通过以下方式进行操作 ' let decodedJson = try! NSJSONSerialization.JSONObjectWithData(data, options: nil) as! NSDictionary'
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-14
相关资源
最近更新 更多