Matteo Villa
Matteo Villa

Reputation: 47

Download and parse a JSON with swift

Can't figure out why this don't work... when i run it, i have this error in the console:

[CONNECTION] OK, data correctly downloaded
[ERROR] An error has happened with parsing of json data
nil

maybe is the JSON format in the link that i pass in the salvaJson() function.

This is the viewController:

//MARK:proprietà
@IBOutlet weak var meteoLabel: UILabel!
@IBOutlet weak var descrizioneLabel: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()

        let data = salvaJson()

        let json = json_parseData(data!)

        print(json)

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


func salvaJson()->NSData?{
    guard let url = NSURL(string: "http://www.medialweb.it/corsi_ok.json") else {
        return nil
    }
    guard let data = NSData(contentsOfURL: url) else {
        print("[ERROR] There is an unspecified error with the connection")
        return nil
    }
    print("[CONNECTION] OK, data correctly downloaded")
    return data
}


// funzione per la generazione del json a partire da un NSData
func json_parseData(data: NSData) -> NSDictionary? {
    do {
        let json: AnyObject = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers)
        print("[JSON] OK!")
        return (json as? NSDictionary)
    } catch _ {
        print("[ERROR] An error has happened with parsing of json data")
        return nil
    }
}

I have removed the comment at the top o JSON. json_parseData()
Now print:[JSON] OK! but i still have nil instead of the printend json

Upvotes: 0

Views: 662

Answers (3)

Nazmul Hasan
Nazmul Hasan

Reputation: 10590

Problem is your JSON cause json result must be start with array

I tested your code it is working code :

guard let url = NSURL(string: "http://pokeapi.co/api/v2/pokemon/1/") else {
            return nil
        } 

Pokemon Webapi and test your json format

UPDATE :

how can i print the error?

     do {
            let json: AnyObject = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers)
            print("[JSON] OK!")
            return (json as? NSDictionary)
        } catch {
            //print("[ERROR] An error has happened with parsing of json data")
            print("\(error)")
            return nil
        }

Upvotes: 1

Chen Wei
Chen Wei

Reputation: 521

agree with Above, you have to make sure your JSON data is in valid format. Try to remove these lines in your JSON data

/**
Export to JSON plugin for PHPMyAdmin
@version 0.1
*/

// Database 'convegnoagi2016_it_db'

// convegnoagi2016_it_db.v_prenotazioni_workshop

Upvotes: 1

tonik12
tonik12

Reputation: 613

The JSON doesn't seem to be valid. Here you can find a JSON validator that fails with the URL you have.

Upvotes: 1

Related Questions