我正在尝试从url(json文件)中获取数据,但在这些行上出现此错误:
I'm trying to take datas from a url (json file) I get this error on these lines:
var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as! NSDictionary if (err != nil) { println("JSON Error \(err!.localizedDescription)") }错误说
线程6:信号SIGABIRT-无法将类型'__NSArrayM'(0x518b58)的值强制转换为'NSDictionary'(0x518d74).
Thread 6: signal SIGABIRT - Could not cast value of type '__NSArrayM' (0x518b58) to 'NSDictionary' (0x518d74).
推荐答案
无论JSON文件数据是什么样的,顶级对象都是一个数组.因为您为options:参数传递了.MutableContainers,所以反序列化将返回可变的数组.
Whatever the JSON file data looks like, the top level object is an array. Because you passed .MutableContainers for the options: argument, the deserialization returns you a mutable array.
您正在强制将其投射到NSDictionary:
You are force-casting this to an NSDictionary:
as! NSDictionary
但是您不能这样做,因为它是一个数组,而不是字典.
But you can't do that because it's an array, not a dictionary.
要做的正确的事情完全取决于我们正在编写代码的目的.
The proper thing to do depends entirely on what we're writing code for.
- 我们是否总是在这里反序列化相同的JSON?它会始终具有相同的结构吗?
如果不是这样,我们需要一种更具动态性的方法.但是如果是这样,此错误将使您清楚地知道要对数组进行反序列化,因此让我们将as! NSDictionary更改为:
If we're not, we need a more dynamic approach. But if we are, this error makes it clear that you're deserializing an array, so let's change as! NSDictionary to:
as NSMutableArray这将做几件事.
由于我们正忙于获取可变对象,因此这将使我们获得可变对象(否则我们不应将其视为可变对象).
Since we're bothing to grab mutable objects, this will give us mutable objects back (otherwise we shouldn't read them as mutable).
我们实际上会读回正确的类型(数组与字典).
We'll actually read the right type back (an array versus a dictionary).
然后通过删除!,我们将返回一个可选内容.好消息是,这意味着我们的代码不会因为收到意外的JSON而崩溃.
And by removing the !, we'll get back an optional. Good news is that this means that our code won't crash just because we got unexpected JSON.
更多推荐
Swift JSON错误,无法将类型'
发布评论