如何在Swift 3中解析JSON数组

我从Socket获取一些我想访问的数据,但我收到的错误是每次都无法将NSArray转换为NSDictionary。

struct SocketEventHandler { let event: String let id: UUID let callback: NormalCallback func executeCallback(with items: [Any], withAck ack: Int, withSocket socket: SocketIOClient) { callback(items, SocketAckEmitter(socket: socket, ackNum: ack)) } } let onFriendRequestStatus: NormalCallback = {dataArray,socketAck in AppLog.debug(tag: TAG, msg: "Response: \(dataArray)") AppLog.debug(tag: TAG, msg: "Response: \(dataArray[0])") let response = dataArray[0] as! Dictionary **// APP CRASHES ON THIS LINE** } 

回应: –

 [ { "status": "A", "acceptorId": 126, "id": 94, "createdAt": "2017-06-05T09:50:42.000Z", "updatedAt": "2017-06-05T09:52:26.000Z", "userId": 126, "friendId": 401 } ] 

错误 – 无法将类型’__NSArrayM’(0x102f0de00)的值转换为’NSDictionary’(0x102f0e2d8)。

可能是你有2d数组意味着dataArray的元素也是Array而不是Dictionary

 if let response = dataArray[0] as? [[String: Any]], let dictionary = response.first { print(dictionary["status"]) } 

在句子崩溃时创建一个断点,然后使用以下命令检查dataArray究竟是什么:

 po print(dataArray)