【发布时间】:2019-01-22 20:35:13
【问题描述】:
我正在从我的服务器获取一个 json。我的服务器 json 是
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
print(userInfo)
}
这个userInfo的打印结果
[AnyHashable("smallIcon"): small_icon, AnyHashable("tickerText"): , AnyHashable("message"): {"action":"new_content_notification","msg":{"headline":"iOS REFERRAL BONUS","subhead":"Congratulations. You have unlocked another BDT500 discount on long route trip booking.","brief":"Congratulations. You have unlocked another BDT500 discount on long route trip booking.","content_id":44}}, AnyHashable("subtitle"): www.ezzyr.com, AnyHashable("sound"): 1, AnyHashable("gcm.message_id"): 0:id, AnyHashable("aps"): {
"content-available" = 1;
},
AnyHashable("title"): Notification from ezzyr, AnyHashable("vibrate"): 1, AnyHashable("largeIcon"): large_icon]
我正在使用 swifty json 进行转换。转换 swity json 后,我得到了这个
let fullInfo = JSON(userInfo)
print(fullInfo)
{
"gcm.message_id" : "0: some number",
"subtitle" : "www.someName.com",
"smallIcon" : "small_icon",
"largeIcon" : "large_icon",
"title" : "Notification from ezzyr",
"vibrate" : "1",
"message" : "{\"action\":\"new_content_notification\",\"msg\":{\"headline\":\"iOS REFERRAL BONUS\",\"subhead\":\"Congratulations. You have unlocked another BDT500 discount on long route trip booking.\",\"brief\":\"Congratulations. You have unlocked another BDT500 discount on long route trip booking.\",\"content_id\":69}}",
"sound" : "1",
"tickerText" : "",
"aps" : {
"content-available" : "1"
}
}
我只想要我的消息密钥中的数据。所以我尝试以这种方式获取消息键值
let message = fullInfo["message"]
print(message)
打印消息后我得到这个结果
{"action":"new_content_notification","msg":{"headline":"iOS REFERRAL BONUS","subhead":"Congratulations. You have unlocked another BDT500 discount on long route trip booking.","brief":"Congratulations. You have unlocked another BDT500 discount on long route trip booking.","content_id":94}}
比我尝试以这种方式获取“动作”的关键值。
let action = message["action"]
print(action)
但是这次我得到的是空值..我怎样才能解决这个问题并获取字符串值以及 msg 的键值
感谢前辈的帮助
【问题讨论】:
-
message 的值是另一个 JSON 字符串。您必须使用
JSONSerialization或Decodable对其进行反序列化,然后才能访问键和值。 -
我该怎么做可以请分享一些例子
-
拜托,关于 JSON 序列化的问题是 SO 上最常见的问题之一。