【问题标题】:String To dictionary Conversion always having Nil values字符串到字典的转换始终具有 Nil 值
【发布时间】:2017-06-19 07:19:43
【问题描述】:

这是一个奇怪的问题。我正在尝试在 Swift 3.0 中将 String 转换为 Dictionary 但字典始终具有 nil 值。不知道为什么

这是我的字符串到字典转换的代码。

 var receivedMessage = [String: String]()
 var MessageReceived:String!

 do
 {
     let jsonData = try JSONSerialization.data(withJSONObject: MessageReceived:String, options: .prettyPrinted)       
     let decoded = try JSONSerialization.jsonObject(with: jsonData, options: [])
     if let dictFromJSON = decoded as? [String:String]
     {                    
          print("MessageReceived",dictFromJSON)
     }
 }
 catch
 {
     print(error.localizedDescription)
 }

而我这里receivedMessage的字符串就是这样的。

{"_id":15, "isMine":true, "isReaded":false, "msgId":"1485956711767", “msgText”:“okkk”,“myId”:“218”,“myJId”:“1101784499938497_218_147300”, "senderName":"Burea", "time":"7:15PM", "timeStamp":1485956711768, "userId":"203", "userJId":"1234840263264009_203_496216" }

我作为字典得到的输出是: 收到消息 [:]

好吧,请帮帮我。 谢谢

【问题讨论】:

  • receivedMessage 已经是 Dictionary 而不是 String。
  • 根据您的代码,receivedMessage 也为空
  • 它是 JSON 字符串而不是字典 @Nirav
  • 是的,当我尝试转换 @in 时收到的消息字典为空
  • json 应该这样转换.. as? [字符串:AnyObject]

标签: ios string dictionary swift3


【解决方案1】:

尝试使用String的data(using:)方法从字符串中获取Data。

if let jsonData = messageReceived.data(using: .utf8) { 
    let decoded = try JSONSerialization.jsonObject(with: jsonData)
    if let dic = decoded as? [String:Any] { //Instead of [String:String] 
         print(dic)
    }
}

【讨论】:

    【解决方案2】:

    你应该做这样的事情,例如

    //your json string 
    let receivedMessage = "{\"_id\":15, \"isMine\":true, \"isReaded\":false, \"msgId\":\"1485956711767\", \"msgText\":\"okkk\", \"myId\":\"218\", \"myJId\":\"1101784499938497_218_147300\", \"senderName\":\"Burea\", \"time\":\"7:15PM\", \"timeStamp\":1485956711768, \"userId\":\"203\", \"userJId\":\"1234840263264009_203_496216\"}"
    //convert that json string into data
    let jsonData = receivedMessage.data(using: .utf8)
    do {
      //decode the json
      let decoded = try JSONSerialization.jsonObject(with: jsonData!)
      // use [String: Any] instead of [String: String] since your some values are int 
      if let dictFromJSON = decoded as? [String: Any] {
        print("MessageReceived", dictFromJSON)
      }
    } catch {
      print(error.localizedDescription)
    }
    

    控制台操作

    MessageReceived ["myId": 218, "senderName": Burea, "myJId": 1101784499938497_218_147300, "_id": 15, "isReaded": 0, "userJId": 1234840263264009_203_496216, "userId": 203, "isM : 1, "msgId": 1485956711767, "msgText": okkk, "timeStamp": 1485956711768, "time": 7:15PM]

    【讨论】:

      猜你喜欢
      • 2019-07-12
      • 2016-04-08
      • 2017-03-03
      • 2021-10-04
      • 1970-01-01
      • 2021-08-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多