Swift JSON错误,无法将类型'

编程入门 行业动态 更新时间:2024-10-09 18:20:09
本文介绍了Swift JSON错误,无法将类型'__NSArrayM'(0x507b58)的值强制转换为'NSDictionary'(0x507d74)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试从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错误,无法将类型'

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

发布评论

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

>www.elefans.com

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