ios - 使用 swift 下载并解析 JSON

标签 ios json swift

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

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

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

这是 View Controller :

//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] OK!但我仍然有 nil 而不是 printend json

最佳答案

问题出在你的 JSON 上,因为 json 结果必须以数组开头

我测试了你的代码,它是工作代码:

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

Pokemon Webapitest your json format

更新:

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
        }

关于ios - 使用 swift 下载并解析 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39484705/

相关文章:

java - 如何为独立的java应用程序存储简单数据

ios - 无法在索引 0 处插入 CAGradientLayer(在 tableView 后面)

ios - 传输安全已阻止明文 HTTP

ios - EKEventKit - 如何在批量提交后检索 eventIdentifier?

json - Play 案例类的json读取和默认参数?

ios - 当 UIContextualAction 的标题为空时,应用程序在 "voice over"中崩溃 - iOS 11

ios - 获得最高可用的 AVCaptureSessionPreset

ios - 检查是否使用控制中心

javascript - Facebook 评论未显示 ios swift

java - jackson :反序列化递归对象