从JSON iOS Swift解析字符串值时获取空值

时间:2019-01-22 09:46:12

标签: ios json swift

我正在从服务器获取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)

但是这次我得到的是空值。如何解决此问题并获取字符串值以及味精的键值

感谢高级帮助

3 个答案:

答案 0 :(得分:1)

我建议完全放弃SwiftyJSON和JSONSerialization,而应使用Codable

使用它来解析message中包含的内部JSON:

struct Message: Codable {
    let action: String
    let msg: Msg
}

struct Msg: Codable {
    let headline, subhead, brief: String
    let contentID: Int

    enum CodingKeys: String, CodingKey {
        case headline, subhead, brief
        case contentID = "content_id"
    }
}

if let messageStr = userInfo["message"] as? String {
  let messageData = messageStr.data(using: .utf8 )!
  let message = try JSONDecoder().decode(Message.self, from: messageData)
}

答案 1 :(得分:0)

正如 vadian先生所说,键 message 的值是另一个JSON字符串,因此要从<< strong>消息,您需要 使用JSONSerialization进行反序列化,如下所示,并获取键 action 的值。

let message = fullInfo["message"] as! String
let data = message.data(using: .utf8)!
do {
    if let messageDict = try JSONSerialization.jsonObject(with: data, options : .allowFragments) as? [String : Any] {
        let action = messageDict["action"] as! String
        print(action)
    } else {
        print("bad json")
    }
} catch let error as NSError {
    print(error)
}

希望这会有所帮助。

答案 2 :(得分:0)

检查:Convert Json string to Json object in Swift 4

转换json中的消息文本:

let messageStr = message as! String
let data = messageStr.data(using: .utf8)!
do {
    if let jsonArray = try JSONSerialization.jsonObject(with: data, options : .allowFragments) as? [Dictionary<String,Any>]
    {
       print(jsonArray) // use the json here    

        let action = jsonArray["action"]
        print(action) // your action is here

    } else {
        print("bad json")
    }
} catch let error as NSError {
    print(error)
}