使用swift下载并解析JSON

时间:2016-09-14 07:24:07

标签: ios json swift

无法弄清楚为什么这不起作用...... 当我运行它时,我在控制台中出现此错误:

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

可能是我在salvaJson()函数中传递的链接中的JSON格式。

这是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
    }
}

我已删除了JSON顶部的评论。 json_parseData()
现在打印:[JSON]好的!但我仍然有nil而不是printend json

3 个答案:

答案 0 :(得分:1)

JSON似乎没有效果。 Here您可以找到失败的JSON验证程序。

答案 1 :(得分:1)

同意上述内容,您必须确保您的JSON数据格式有效。尝试删除JSON数据中的这些行

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

// Database 'convegnoagi2016_it_db'

// convegnoagi2016_it_db.v_prenotazioni_workshop

答案 2 :(得分:1)

问题是您的JSON原因json结果必须以数组

开头

我测试了你的代码,它正在运行代码:

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

Pokemon Webapitest your json format

更新:

  

我该如何打印错误?

     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
        }