[英]Extract data from nested JSON in Firebase remoteMessage
我正在迅速開發一個消息傳遞應用程序。 我配置了Firebase雲消息傳遞,並且可以正常工作,數據到達了我的手機。
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)
}
}
它在第一行給了我這個錯誤。
*由於未捕獲的異常'NSInvalidArgumentException'而終止應用程序,原因:'* + [NSJSONSerialziation dataWithJSONObject:options:error:]:JSON寫入中的無效頂級類型'
我遵循了這篇文章的建議,但也沒有運氣。
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)
無法將類型'__NSCFString'(0x1e0e52f90)的值強制轉換為'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字符串而不是字典
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.