【问题标题】:Getting null value when parsing string value from json iOS swift从 json iOS swift 解析字符串值时获取空值
【发布时间】: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 字符串。您必须使用JSONSerializationDecodable 对其进行反序列化,然后才能访问键和值。
  • 我该怎么做可以请分享一些例子
  • 拜托,关于 JSON 序列化的问题是 SO 上最常见的问题之一。

标签: ios json swift


【解决方案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)
}

【讨论】:

  • xcode 抱怨将 'decoder' 替换为 'decode .. 自动完成后说无法将类型 '[AnyHashable : Any]' 的值转换为预期的参数类型 'Data'
  • 我正在从 userinfo 获取数据,但是当我传递这个变量时,我在这里遇到了同样的错误,我通过了什么,让 fullInfo = try JSONDecoder().decode(FullInfo.self, from: userInfo)
  • 它给出错误“无法将类型 '[AnyHashable : Any]' 的值转换为预期的参数类型 'Data'”
  • 看起来您正在传递初始 JSONSerialization 调用的结果。不要那样做,将原始数据传递给解码器(即,您用来获取该字典的任何内容。
  • 我更新了我的问题希望它能帮助你理解我的问题..
【解决方案2】:

检查这个: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)
}

【讨论】:

  • 收到此错误,“JSON”类型的值在第一行没有成员“数据”
  • 当我们有Codable时,请不要推荐使用JSONSerialization
【解决方案3】:

正如vadian sir所说,message键的值是另一个JSON字符串,所以要从action中获取action的值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)
}

希望这会有所帮助。

【讨论】:

  • 我在运行时遇到错误,因为第一行执行错误
猜你喜欢
  • 2018-04-13
  • 2016-08-15
  • 2013-02-13
  • 1970-01-01
  • 1970-01-01
  • 2019-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多