【问题标题】:Swift JSON error : Could not cast value of type '__NSDictionaryM' to 'NSArray'Swift JSON 错误:无法将“__NSDictionaryM”类型的值转换为“NSArray”
【发布时间】:2015-12-02 18:40:48
【问题描述】:

从 webservice(API) 解码 JSON 时出现错误:

Could not cast value of type '__NSDictionaryM' (0x1037ad8a8) to 'NSArray' (0x1037ad470). 

我的代码:

var kGetURL = "http://bitnami.local/cscart_demo/api/users"

//var kGetURL = "http://localhost/fendy/getjson.php"

var json : Array<AnyObject> = []

 override func viewDidLoad() {
    super.viewDidLoad()
    start()
 }

 func getData(data : NSData){
    //error at this line :
    json = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as! Array<AnyObject>
    //error
    tableView.reloadData()
}

func start(){ 
    var url : NSURL = NSURL(string: kGetURL)!
    var data : NSData = NSData(contentsOfURL: url)!
    getData(data)
}

如果我将 url 更改为 http://localhost/fendy/getjson.php,它的工作非常好。

如果我的网址是http://bitnami.local/cscart_demo/api/users,我会收到错误

来自网络服务http://localhost/fendy/getjson.php 的响应:

 [{"id":"17","Name":"KFC","Message":"awesome"},
{"id":"18","Name":"McDonald","Message":"good"},
{"id":"23","Name":"Burger King","Message":"tasty"},
{"id":"38","Name":"Pizza hut","Message":"yummy"},
{"id":"39","Name":"Steak","Message":"very Delicious"}]

来自网络服务http://bitnami.local/cscart_demo/api/users 的响应:

 {"users":
[{"user_id":"4","user_login":"user_4","is_root":"N","timestamp":"1441608048","user_type":"C","status":"A","firstname":"","lastname":"","email":"fendy.w@mvig.net","company":"","company_id":"1","company_name":"Simtech"},
{"user_id":"3","user_login":"customer","is_root":"N","timestamp":"1441604240","user_type":"C","status":"A","firstname":"Customer","lastname":"Customer","email":"customer@example.com","company":"Simtech","company_id":"1","company_name":"Simtech"},
{"user_id":"1","user_login":"admin","is_root":"Y","timestamp":"1441604240","user_type":"A","status":"A","firstname":"John","lastname":"Doe","email":"robby@mvig.net","company":"Your company","company_id":"0","company_name":null}],
"params":{"page":1,"items_per_page":"10","sort_order":"asc","sort_by":"name","sort_order_rev":"desc","total_items":"3"}}

我认为它的风格是相同的,但为什么不使用 url http://bitnami.local/cscart_demo/api/users 。有人可以帮忙吗?

【问题讨论】:

    标签: ios json swift


    【解决方案1】:

    bitnami 响应以{ 开头,因此它是JSON object,对应于NSDictionary。另一个以[ 开头,表示一个数组。

    需要将json的类型改为Dictionary&lt;String, AnyObject&gt;,反序列化如下:

    json = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as! Dictionary<String, AnyObject>
    

    【讨论】:

    • 如果我使用 json 类型数据 NSDictionary?这是可能的?在 tableView CellforRowIndexPath 我改变: var info : AnyObject? = json[indexpath.row] ?
    【解决方案2】:

    您的方法是将 JSON 结果转换为数组。它适用于返回表示为 JSON 的数组的 URL,但不适用于返回字典而不是数组的 URL,表示为 JSON。

    虽然返回值的“风格”看起来一样,但第二个是单项字典。您可能想要从中提取 "users" 元素,这是一个数组。

    如果您不知道要获取的两个 URL 中的哪一个,您可以尝试使用 as? 转换而不是 as! 两种样式:

    let tmp : AnyObject! = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil)
    if let arr = tmp as? Array<AnyObject> {
        json = arr
    } else if dict = tmp as? [String: AnyObject] {
        json = dict["users"] as! Array<AnyObject>
    } else {
        // Handle an error: the input was unexpected
    }
    tableView.reloadData()
    

    【讨论】:

    • 那么,类型数据变量json必须是NSDictionary吗?按照你的例子我得到错误:如果让 arr ? Array { // 条件中的变量绑定需要初始化器
    • @fendy 你说得对,我忘了做作业。立即尝试。
    【解决方案3】:

    尝试缓存以进行序列化

            do {
                if let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String : Any] { // as? data type
                    if let otherDict = json["dataKey"] as? [String : Any] {
                        //do something
                    }
                }
            } catch {
                // can't json serialization
            }
    

    【讨论】:

    • 这个页面上已经有很好的答案了。在这里使用 NSDictionary 不是最优的,最好使用 Swift 的字典。正如其他答案中所解释的......
    • 只是改成? [字符串:任意]
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多