简体   繁体   English

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

[英]Extract data from nested JSON in Firebase remoteMessage

I am developing a messaging app in swift. 我正在迅速开发一个消息传递应用程序。 I configured firebase cloud messaging and it works, the data arrives to my phone. 我配置了Firebase云消息传递,并且可以正常工作,数据到达了我的手机。

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

Problem is, I don't know how to extract each value. 问题是,我不知道如何提取每个值。 This is a example of output I receive from the server. 这是我从服务器收到的输出示例。

[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]

I've tried reading it as a JSON but it doesn't work. 我尝试将其读取为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)
    }
}

It gives me this error on the first line. 它在第一行给了我这个错误。

* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '* +[NSJSONSerialziation dataWithJSONObject:options:error:]: Invalid top-level type in JSON write' *由于未捕获的异常'NSInvalidArgumentException'而终止应用程序,原因:'* + [NSJSONSerialziation dataWithJSONObject:options:error:]:JSON写入中的无效顶级类型'

I followed the suggestions on this post, but no luck either. 我遵循了这篇文章的建议,但也没有运气。

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). 无法将类型'__NSCFString'(0x1e0e52f90)的值强制转换为'NSDictionary'(0x1e0e53bc0)。

You need 你需要

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
}

as message key contains a json String not a dictionary 作为message键包含json字符串而不是字典

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM