1
"{\"event\":\"posted\",\"data\":{\"channel_display_name\":\"\",\"channel_name\":\"e6webbgbt7gp8ryb4yyheiyrcw__jbk5semtk3dhjqzcoscu7g4yhe\",\"channel_type\":\"D\",\"mentions\":\"[\\\"jbk5semtk3dhjqzcoscu7g4yhe\\\"]\",\"post\":\"{\\\"id\\\":\\\"4fu4ey9fwfbyzndnz6brycmcry\\\",\\\"create_at\\\":1516692235168,\\\"update_at\\\":1516692235168,\\\"edit_at\\\":0,\\\"delete_at\\\":0,\\\"is_pinned\\\":false,\\\"user_id\\\":\\\"e6webbgbt7gp8ryb4yyheiyrcw\\\",\\\"channel_id\\\":\\\"6jc3md8ayfycxb87fqz63jphia\\\",\\\"root_id\\\":\\\"\\\",\\\"parent_id\\\":\\\"\\\",\\\"original_id\\\":\\\"\\\",\\\"message\\\":\\\"dd\\\",\\\"type\\\":\\\"\\\",\\\"props\\\":{},\\\"hashtags\\\":\\\"\\\",\\\"pending_post_id\\\":\\\"e6webbgbt7gp8ryb4yyheiyrcw:1516692235123\\\"}\",\"sender_name\":\"bibek\",\"team_id\":\"\"},\"broadcast\":{\"omit_users\":null,\"user_id\":\"\",\"channel_id\":\"6jc3md8ayfycxb87fqz63jphia\",\"team_id\":\"\"},\"seq\":9}"

Above is the string that I get from a websocket. When I parse it to json using:

guard let data = text.data(using: .utf8) else {return}
let json = try? JSONSerialization.jsonObject(with: data, options: [])

I get:

{
  "event" : "posted",
  "data" : {
    "channel_display_name" : "",
    "channel_name" : "e6webbgbt7gp8ryb4yyheiyrcw__jbk5semtk3dhjqzcoscu7g4yhe",
    "sender_name" : "bibek",
    "post" : "{\"id\":\"4fu4ey9fwfbyzndnz6brycmcry\",\"create_at\":1516692235168,\"update_at\":1516692235168,\"edit_at\":0,\"delete_at\":0,\"is_pinned\":false,\"user_id\":\"e6webbgbt7gp8ryb4yyheiyrcw\",\"channel_id\":\"6jc3md8ayfycxb87fqz63jphia\",\"root_id\":\"\",\"parent_id\":\"\",\"original_id\":\"\",\"message\":\"dd\",\"type\":\"\",\"props\":{},\"hashtags\":\"\",\"pending_post_id\":\"e6webbgbt7gp8ryb4yyheiyrcw:1516692235123\"}",
    "channel_type" : "D",
    "team_id" : "",
    "mentions" : "[\"jbk5semtk3dhjqzcoscu7g4yhe\"]"
  },
  "seq" : 9,
  "broadcast" : {
    "channel_id" : "6jc3md8ayfycxb87fqz63jphia",
    "omit_users" : null,
    "user_id" : "",
    "team_id" : ""
  }
}

you can see that "post" key has still string value. How can I convert that to json in one shot?

Bibek
  • 3,689
  • 3
  • 19
  • 28

2 Answers2

2

There are two ways to parsing a JSON.

Before Swift 4

Before Swift 4 you could only use JSONSerialization Class (like in your example). This method return a Any object that can be cast in a Dictionary (the type depends on the data you are receiving).

For example:

if let dict = try? JSONSerialization.jsonObject(with: data, options: []) as! Dictionary<String,String>{
   do some stuff...
}

If you have multiple kind of data you should use this casting:

  if let dict = try? JSONSerialization.jsonObject(with: data, options: []) as! Dictionary<String,Any?>{
       do some stuff...
    }

Then you can access to all the data in the dictionary by the key and manage the data (if you use Any remember to cast in the correct data before using them).

Here some documentation: https://developer.apple.com/documentation/foundation/jsonserialization

After Swift 4

With Swift 4 a new class was introduced: JSONEncoder and JSONDecoder. It's amazing, because you can create your model, parsing the json and you'll get an object with all the fields already filled. Pay attention that your model MUST implements the protocol Codable (or Encodable and Decodable). If your model doesn't implements the protocol you'll get an error.

Here an example:

This is my model:

class myClass: Codable{
    var Id: Int
    var Identifier: String
    var Alias: String
    var Revision: Int
    var Title: String
}

And this is the code for the parsing:

let decoder = JSONDecoder()

let myClass = try! decoder.decode(Questionario.self, from: (json?.data(using: .utf8))!)

Now my variable "myClass" already contains all the field filled with the data in the json.

Here some documentation:

https://developer.apple.com/documentation/swift/codable

https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types

Fab
  • 816
  • 8
  • 17
0

try

let data = text.data(using: .utf8)
let json = try? JSONSerialization.jsonObject(with: data!, options: [])
if let value = json as? [String:AnyObject]{
if let dict = value["data"] as? NSDictionary{
    let post = dict.value(forKey: "post") as? String
    let data = post!.data(using: .utf8)
    let json1 = try? JSONSerialization.jsonObject(with: data!, options: [])
    print(json1!)
}
}

as I got post in JSON form let me know for any corrections