Json序列化Swift 3类型错误 [英] Json Serialisation Swift 3 type error
本文介绍了Json序列化Swift 3类型错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用以下代码从推送通知中接收自定义数据,并且出现以下错误:
I am using the following code to receive custom data from a push notification and I get the following error:
无法将类型'__NSArrayM'(0x1b0776cf0)的值强制转换为'NSDictionary'(0x1b0777128).
Could not cast value of type '__NSArrayM' (0x1b0776cf0) to '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"]!)")
}
推荐答案
读取错误:
无法将期望类型的数组的值强制转换为提供类型的字典
Could not cast value of expected type Array to offered type Dictionary
这意味着您的JSON是一个数组,所以
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]]
...
您可以省略options
参数,因为.mutableContainers
在Swift中还是没用的.
You can omit the options
parameter, because .mutableContainers
is useless in Swift anyway.
这篇关于Json序列化Swift 3类型错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文