首页 文章

无法将'__NSCFString'类型的值转换为'NSDictionary'

提问于
浏览
-1

我想访问另一个json中我的Json的一些数据

这是我的代码:

let extraData = userInfo["extraData"] as! [String : Any]
print(extraData["message_id"])

但运行时我得到以下错误:

Could not cast value of type '__NSCFString' (0x264300f90) to 'NSDictionary' (0x264301bc0)

这是我的Json:

[AnyHashable(“largeIcon”):http://test.png,AnyHashable(“notifyType”):notifyData,AnyHashable(“ledColor”):#f39c12,AnyHashable(“extraData”):{“is_background”:0, “message_id”:“1156”,“deep_link”:{“action_type”:“U”,“url”:“teknik:// teknik”}},AnyHashable(“message”):test,AnyHashable(“id”) :50368138,AnyHashable(“vibrate”):1,AnyHashable(“gcm.message_id”):0:1544436390847%bebba17fbebba17f,AnyHashable(“autoRun”):false,AnyHashable(“action”):{“type”:“A “,”url“:”Activity.MessageActivityJava“},AnyHashable(”sound“):3,AnyHashable(”title“):newtest,AnyHashable(”aps“):{”content-available“= 1; }]

2 回答

  • 0

    在这种情况下,你的“extraData”数据是JSON字符串所以它不能直接转换为字典你需要将字符串转换为字典,然后使用如下的特定键提取数据 .

    func convertToDictionary(text: String) -> [String: Any]? {
        if let data = text.data(using: .utf8) {
            do {
                return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
            } catch {
                print(error.localizedDescription)
            }
        }
        return nil
    }
    
    let extraDataStr =  userInfo["extraData"] as! String    
    let dict = convertToDictionary(text: extraDataStr)
    print(dict?["message_id"] as! String)
    

    有关此帖子的详细信息,请参阅How to convert a JSON string to a dictionary?

  • 0

    你可以试试

    do { 
      let dd =  userInfo["extraData"] as! String  
      let con = try JSONSerialization.jsonObject(with: dd.data(using: .utf8)!, options: []) as! [String:Any]
      print(con["message_id"]) 
    catch {
       print(error)
    }
    

    as extraData value是一个json字符串而不是直接字典

相关问题