How to parse array of JSON in Swift 3 [duplicate]

2019-03-07 01:03发布

This question already has an answer here:

I am getting some data from Socket which I would like to access but I am getting error saying can't convert NSArray to NSDictionary each time.

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<String, Any> **// APP CRASHES ON THIS LINE**
}

Response :-

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

Error - Could not cast value of type '__NSArrayM' (0x102f0de00) to 'NSDictionary' (0x102f0e2d8).

2条回答
在下西门庆
2楼-- · 2019-03-07 02:01

Make a breakpoint on sentence crashes, and then use following command to check what exactly the dataArray is:

po print(dataArray)
查看更多
别忘想泡老子
3楼-- · 2019-03-07 02:02

May be you are having 2d array means the elements of dataArray are also Array not Dictionary.

if let response = dataArray[0] as? [[String: Any]], let dictionary = response.first {

    print(dictionary["status"])
}
查看更多
登录 后发表回答