You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift中NSArray转NSDictionary报错:无法将__NSArrayM转为NSDictionary

解决JSON数组转NSDictionary的类型转换错误

嘿,这问题我熟!你肯定是没注意到JSON的结构类型——你拿到的是数组格式的JSON([ {},{},{}]),但代码里却硬要把它转换成NSDictionary,这不就触发类型不匹配的错误了嘛!

先看看你遇到的错误提示:

Could not cast value of type '__NSArrayM' (0x11038e2b8) to 'NSDictionary' (0x11038fa78).
2019-08-09 16:14:43.360585+0530 Consultation[2699:64715] Could not cast value of type '__NSArrayM' (0x11038e2b8) to 'NSDictionary' (0x11038fa78).

问题根源

JSON里的[]代表数组,对应Swift/OC里的NSArray或者Swift原生[[String: Any]];而{}才是字典,对应NSDictionary或者Swift原生[String: Any]。你现在把数组硬转成字典,当然会报错啦!

修改后的代码方案

给你两种写法,按需选择:

方案一:兼容OC的NSArray/NSDictionary写法

if let data = data { 
    do { 
        // 先解析成任意类型,再判断实际类型
        let jsonObject = try JSONSerialization.jsonObject(with: data)
        if let jsonArray = jsonObject as? NSArray {
            print("成功解析为数组:", jsonArray)
            // 遍历数组里的字典元素
            for item in jsonArray {
                if let dict = item as? NSDictionary {
                    print("数组中的字典元素:", dict)
                }
            }
        } else if let jsonDict = jsonObject as? NSDictionary {
            print("意外解析为字典:", jsonDict)
        }
    } catch { 
        print("解析出错:", error.localizedDescription) 
    } 
}

方案二:更Swift风格的原生类型写法

if let data = data { 
    do { 
        // 直接解析成Swift原生的字典数组
        if let jsonArray = try JSONSerialization.jsonObject(with: data) as? [[String: Any]] {
            print("成功解析为Swift数组:", jsonArray)
            // 遍历处理每个字典
            for item in jsonArray {
                print("数组中的字典元素:", item)
            }
        }
    } catch { 
        print("解析出错:", error.localizedDescription) 
    } 
}

小提示

以后解析JSON时,先确认接口返回的结构是数组还是对象,再对应转换类型。尽量避免用as!强制转换,用as?做可选绑定更安全,不会因为类型不匹配导致App崩溃哦~

内容的提问来源于stack exchange,提问作者Swamy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 06:42:17