d0ve
d0ve

Reputation: 63

Parsing JSON into swift predefined array

I am trying to get items from an api (JSON) and to parse it into a predefined swift array. I have searched and looked for hours but due to my lack of skills I wasn't able to find anything suitable my case.

My predefined array looks like this:

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

the JSON structure is like this(entire json file):

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

My current code looks like this (Games is the class where I connect variables from array with table cell items):

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)
}

I am getting the following error:

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

EDIT: The error is being thrown here:

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

Your help is highly appreciated. Thanks in advance!

Upvotes: 1

Views: 92

Answers (2)

Med Abida
Med Abida

Reputation: 1222

hello your data variable doesn't contain the Json you r looking for. so you have to serialize it to json like alexander suggested but NSJSONSerialization can throw an error so we have tu put in in try so your code will be something like this (i suggest always using dispatch_async to make it in background thread than use the completion closure to get your result)-->

    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: please let me know if you need more help.

Upvotes: 1

Alexander Gaidukov
Alexander Gaidukov

Reputation: 759

Your data variable is NSData type (not NSDictionary). You have to convert it in order to use it. Try something like that:

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

And than you can use it like standard dictionary

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

Upvotes: 0

Related Questions