【问题标题】:unexpectedly found nil while unwrapping an Optional value reading JSON在打开读取 JSON 的可选值时意外发现 nil
【发布时间】:2015-05-05 23:04:04
【问题描述】:

人们,我不明白为什么,但是这个问题(在展开 Optional 值时意外发现 nil)发生在这一行:

var dict: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &error) as NSDictionary

查看代码:

导入基础

类产品服务 {

// return a produtos Array
class func getProdutos() -> Array<Produto> {

    var produtos: Array<Produto> = []

    for (var i = 0; i < 10; i++) {
        var p = Produto()
        p.nome = "Produto \(i)"
        p.desc1 = "Descrição \(i)"
        p.desc2 = "Descrição \(i)"

        produtos.append(p)
    }

    return produtos
}

// get from JSON
class func getProdutosByJson() -> Array<Produto> {

    let path = NSBundle.mainBundle().pathForResource("produtos", ofType: "json")!
    let data = NSData(contentsOfFile: path)

    let produtos = parserJson(data!)

    return produtos
}

class func parserJson(data: NSData) -> Array<Produto> {

    if (data.length == 0) {
        println("NSData vazio")
        return []
    }

    var produtos: Array<Produto> = []

    // read JSON and convert to Dictionary
    var error: NSError?
    var dict: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &error) as NSDictionary

    // read the structure Produtos and return a array with JSON content
    var jsonProdutos: NSDictionary = dict["produtos"] as NSDictionary
    var arrayProdutos: NSArray = jsonProdutos["produto"] as NSArray

    // Array produtos

    for obj:AnyObject in arrayProdutos {
        var dict = obj as NSDictionary
        var produto = Produto()
        produto.nome = dict["nome"] as String
        produto.desc1 = dict["desc1"] as String
        produto.desc2 = dict["desc2"] as String
        produtos.append(produto)
    }

    return produtos
}

}

【问题讨论】:

  • 我相信这意味着您的 JSON 无法解析为 NSDictionary 结构。它可能是空的,也可能是一个 NSArray。

标签: ios json swift xcode6 optional


【解决方案1】:

带有数据的 JSONObject 似乎返回 NIL,因为数据可能无效。 检查错误参数的内容!

作为一种解决方案,您应该在读取 JSON 数据源之前对其进行检查。使用 NSJSONSerialization.isValidJSONObject 成员函数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-11
    • 1970-01-01
    相关资源
    最近更新 更多