展开读取JSON的可选值时意外发现nil

编程入门 行业动态 更新时间:2024-10-25 16:16:49
本文介绍了展开读取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

本文发布于:2023-11-26 14:08:27,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1634088.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:可选   意外   发现   JSON   nil

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!