2017-03-29 7 views
-3

ich den folgenden Code verwende benutzerdefinierte Daten von einer Push-Benachrichtigung zu erhalten und ich erhalte den folgenden Fehler:Json Serialisierung Swift 3-Typ Fehler

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

auf der folgenden Zeile:

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

Wie behebe ich diesen Fehler?

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"]!)") 
    } 
+0

Offensichtlich ist das JSON ein Array, kein Wörterbuch. Und warum wirst du gewirkt? – rmaddy

Antwort

2

den Fehler Lesen:

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

Das Ihre JSON bedeutet ein Array, so

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

Sie können die options Parameter weglassen, weil .mutableContainers in Swift ohnehin nutzlos.

+0

Vielen Dank – MattBlack