Mad Burea Mad Burea - 4 years ago 124
iOS Question

String To dictionary Conversion always having Nil values

It's strange issue here. i am trying to convert String into Dictionary in Swift 3.0 but dictionary always having nil values. i Don't know why

here is my code for String to Dictionary Conversion.

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

do {
let jsonData = try MessageReceived:String, options: .prettyPrinted)

let decoded = try JSONSerialization.jsonObject(with: jsonData, options: [])

if let dictFromJSON = decoded as? [String:String] {


} catch {

And My String that is here receivedMessage is like this.

{"_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" }

and the output that i get as a dictionary is:
received message [:]

Well Please help me.

Answer Source

Try to get Data from string using data(using:) method of String.

if let jsonData = .utf8) { 
    let decoded = try JSONSerialization.jsonObject(with: jsonData)
    if let dic = decoded as? [String:Any] { //Instead of [String:String] 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download