【问题标题】:Json Serialisation Swift 3 type errorJson 序列化 Swift 3 类型错误
【发布时间】:2017-03-29 19:24:43
【问题描述】:

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

无法将“__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"]!)")
    }

【问题讨论】:

  • 显然 JSON 是一个数组,而不是字典。你为什么要强制转换?

标签: json swift swift3


【解决方案1】:

读取错误:

无法将 expected 类型 Array 的值转换为 offered 类型 Dictionary

这意味着你的 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 中无论如何都没用。

【讨论】:

  • 非常感谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-22
  • 1970-01-01
  • 2017-01-24
相关资源
最近更新 更多