json - 快速下载和解析 json

标签 json parsing swift

我正在尝试从网站获取 JSON 并在将其放入 iOS View 之前对其进行解析。

这是我的代码;

func startConnection(){
        let urlPath: String = "http://binaenaleyh.net/dusor/"
        var url: NSURL = NSURL(string: urlPath)
        var request: NSURLRequest = NSURLRequest(URL: url)
        var connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: false)
        connection.start()
    }

    func connection(connection: NSURLConnection!, didReceiveData data: NSData!){
        self.data.appendData(data)
    }

    func buttonAction(sender: UIButton!){
        startConnection()
    }

    func connectionDidFinishLoading(connection: NSURLConnection!) {
        var err: NSError
        // throwing an error on the line below (can't figure out where the error message is)
        var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
    }

这是 JSON 的链接;

http://binaenaleyh.net/dusor/

我在这里做错了什么?

最佳答案

这两个功能对我有用:

    func getJSON(urlToRequest: String) -> NSData{
        return NSData(contentsOfURL: NSURL(string: urlToRequest))
    }

    func parseJSON(inputData: NSData) -> NSDictionary{
        var error: NSError?
        var boardsDictionary: NSDictionary = NSJSONSerialization.JSONObjectWithData(inputData, options: NSJSONReadingOptions.MutableContainers, error: &error) as NSDictionary

        return boardsDictionary
    }

关于json - 快速下载和解析 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24065536/

相关文章:

php - 使用 PDO 从两个表中获取 JSON

jquery - 将数组从 jQuery 传递到 MVC.NET Controller ,在 Controller 上给出 null 结果,但 jQuery 函数上存在值

php - 将 PHP Doc 注释解析为数据结构

c++ - 如何使用 C++ 和 Window.h 解析 EXE 文件并从 IMAGE_DOS_HEADER 结构中获取数据?

python - 将 JSON 文件转换为具有定义格式的 Dataframe

javascript - 访问 Json 对象

java - 解析UDP数据包后输出垃圾

使用世界地图在 uiimageview 上快速绘制坐标

ios - Swift:JSONEcoder EXC_BAD_ACCESS

ios - Swift - 通过动态类型加载类