人们,我不明白为什么,但是此行中发生了此问题(在包装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
发布评论