Swift-读取JSON文件 [英] Swift - Reading JSON File

查看:475
本文介绍了Swift-读取JSON文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Swift的新手-尝试从URL读取JSON文件.我在下面的尝试.

I'm new to Swift - trying to read a JSON file from a URL. My attempt below.

JSON看起来有效-我用JSONLint测试了它,但它一直崩溃.

The JSON looks valid - I tested it with JSONLint but it keeps crashing.

有想法吗?

func getRemoteJsonFile() -> NSDictionary {
    //Create a new url

    let remoteUrl:NSURL? = NSURL(string: "http://nfl-api.azurewebsites.net/myplayers.json")

    //check if its nil
    if let actualRemoteUrl = remoteUrl {

        //try to get the data
        let filedata:NSData? = NSData(contentsOfURL: actualRemoteUrl)

            //check if its nil
        if let actualFileData = filedata {

            //parse out the dictionaries
            let jsonDict = NSJSONSerialization.JSONObjectWithData(actualFileData, options: NSJSONReadingOptions.AllowFragments, error: nil) as NSDictionary

            return jsonDict
        }
    }
        return NSDictionary()
}

推荐答案

使用以下方法更新代码:

Update your code with this:

func getRemoteJsonFile() -> [NSDictionary] {

    // Create a new URL
    let remoteUrl:NSURL? = NSURL(string: "http://nfl-api.azurewebsites.net/myplayers.json")

    let urlString:String = "\(remoteUrl)"

    // Check if it's nil
    if let actualRemoteUrl = remoteUrl {

        // Try to get the data
        let fileData:NSData? = NSData(contentsOfURL: actualRemoteUrl)

        // Check if it's nil
        if let actualFileData = fileData {

            // Parse out the dictionaries
            let arrayOfDictionaries:[NSDictionary]? = NSJSONSerialization.JSONObjectWithData(actualFileData, options: NSJSONReadingOptions.MutableContainers, error: nil) as [NSDictionary]?

            if let actualArrayOfDictionaries = arrayOfDictionaries {

                // Successfully parsed out array of dictionaries
                return actualArrayOfDictionaries
            }
        }

    }
    return [NSDictionary]()
}

这对我来说很好.

这篇关于Swift-读取JSON文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆