展开读取JSON的可选值时意外发现nil [英] unexpectedly found nil while unwrapping an Optional value reading JSON

查看:154
本文介绍了展开读取JSON的可选值时意外发现nil的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

人们,我不明白为什么,但是此行中发生了此问题(在包装Optional值时意外发现为nil):

people, I can not understand why, but this problem (unexpectedly found nil while unwrapping an Optional value) happens in this line:

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

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

查看代码:

导入基金会

ProdutoService类{

class ProdutoService {

// 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
}

}

推荐答案

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

JSONObject with data seems to return NIL, because the data may be invalid. Check the content of the error parameter!

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

As a solution, you should check the JSON datasource before reading from it. Use the NSJSONSerialization.isValidJSONObject member function.

这篇关于展开读取JSON的可选值时意外发现nil的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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