Json Serialisation Swift 3 type error

2019-03-07 05:45发布

I am using the following code to receive custom data from a push notification and I get the following error:

Could not cast value of type '__NSArrayM' (0x1b0776cf0) to 'NSDictionary' (0x1b0777128).

on the following line:

let jsonData = try? JSONSerialization.jsonObject(with: (customDataString?.data(using: String.Encoding.utf8))!, options: JSONSerialization.ReadingOptions.mutableContainers) as![String: Any]

How do I resolve this error?

func onPushAccepted(_ pushManager: PushNotificationManager!, withNotification pushNotification: [AnyHashable : Any]!, onStart: Bool) {
    print("Push notification accepted: \(pushNotification!)")

    let customDataString = pushManager.getCustomPushData(pushNotification)

    if customDataString != nil {
        let jsonData = try? JSONSerialization.jsonObject(with: (customDataString?.data(using: String.Encoding.utf8))!, options: JSONSerialization.ReadingOptions.mutableContainers) as! [String: Any]

        print("*** \(jsonData?["test"]!)")
    }

1条回答
虎瘦雄心在
2楼-- · 2019-03-07 06:25

Read the error:

Could not cast value of expected type Array to offered type Dictionary

That means your JSON is an array, so

if let customDataString = pushManager.getCustomPushData(pushNotification) {   
   let data = customDataString.data(using: utf8)!
   let jsonData = try? JSONSerialization.jsonObject(with: data) as! [[String:Any]]
   ...

You can omit the options parameter, because .mutableContainers is useless in Swift anyway.

查看更多
登录 后发表回答