Json Serialization Swift 3类型错误

时间:2017-03-29 19:24:43

标签: json swift swift3

我使用以下代码从推送通知接收自定义数据,我收到以下错误:

  

无法将'__NSArrayM'(0x1b0776cf0)类型的值转换为'NSDictionary'(0x1b0777128)。

在以下一行:

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

如何解决此错误?

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 个答案:

答案 0 :(得分:2)

阅读错误:

  

无法将预期类型数组的值转换为提供类型字典

这意味着你的JSON是一个数组,所以

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

您可以省略options参数,因为.mutableContainers无论如何都无法在Swift中使用。