从 Firebase remoteMessage 中的嵌套 JSON 中提取数据

Extract data from nested JSON in Firebase remoteMessage

我正在 swift 开发消息应用程序。我配置了 firebase 云消息传递并且它有效,数据到达我的 phone.

func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
    print(remoteMessage.appData)
}

问题是,我不知道如何提取每个值。这是我从服务器收到的输出示例。

[AnyHashable("message"): {"chat":{"msg":"hey","file":null,"to":"username","date":"2019\/03\/06 08:17:42","group":"TESTING","from":"User Real Name","res":"1"}}, AnyHashable("from"): 123123123]

我试过 JSON 阅读它,但它不起作用。

let data = try? JSONSerialization.data(withJSONObject: remoteMessage.appData["message"]
if let messageJSON = try? JSONSerialization.jsonObject(with: data!) as? [String : Any] {
    print(messageJSON
    if let chatJSON = messageJSON["chat"] as? [String : Any] {
        print(chatJSON)
    }
}

它在第一行给我这个错误。

* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '* +[NSJSONSerialziation dataWithJSONObject:options:error:]: Invalid top-level type in JSON write'

我遵循了 post 上的建议,但也不走运。

let d: [String : Any] = remoteMessage.appData["message"] as! [String : Any]
let body: [String : Any] = d["chat"] as! [String : Any]
let msg: String = body["msg"] as! String
print(msg)

Could not cast value of type '__NSCFString' (0x1e0e52f90) to 'NSDictionary' (0x1e0e53bc0).

你需要

do {
  let d  = remoteMessage.appData["message"] as! String
  let res = try JSONDecoder().decode(Root.self,from:Data(d.utf8)) 
  print(res)
}
catch {
 print(error)
}

struct Root: Codable {
    let chat: Chat
}

struct Chat: Codable {
    let msg: String
    let file: String?
    let to, date, group, from: String
    let res: String
}

因为 message 键包含一个 json 字符串而不是字典