json - 从 Firebase remoteMessage 中的嵌套 JSON 中提取数据
问题描述
我正在快速开发一个消息传递应用程序。我配置了 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字符串而不是字典
推荐阅读
- python - Pandas Dataframe:过滤使用列定义的条件
- node.js - sequelize include,连接两个关联表
- python - 无法在 REFRESH_TOKEN_AUTH 验证客户端的秘密哈希
- excel - Excel公式将一个表中的单元格与另一表中的单元格匹配并返回总和值
- javascript - 如果 Web 应用的 CacheStorage 缓存内容过多,应用会崩溃吗?
- elasticsearch - 别名上的 ElasticSearch 在 5 天后无法正常工作
- python-3.x - 如何使用python list将5个连续的1减少为一个
- powerbi - 如何获取 Power BI Desktop 度量中空白的默认字符串值
- javascript - 光照贴图只适用于静态场景吗?
- ios - 如何在闭包中使用 self 来防止内存泄漏