如何正确解析嵌套的json字符串到正确的json?

时间:2018-01-23 07:38:59

标签: ios json swift4 json-serialization

abstract class Animal {            
  def giveAnimalData(): DataFrame            
}

// The following must be a singleton.
// I have to implement all my logic in this class and acquire all the features of Animal
class GenerateCountryAnimal(tableA: Table, tableB: Table) extends Animal {
  // implement giveAnimalData method
}

上面是我从websocket获得的字符串。 当我使用:

将其解析为json时
"{\"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}"

我明白了:

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

你可以看到“post”键仍然是字符串值。 我如何一次性将其转换为json?

2 个答案:

答案 0 :(得分:1)

解析JSON有两种方法。

在Swift 4之前

在Swift 4之前,你只能使用JSONSerialization Class(就像在你的例子中一样)。此方法返回可以在Dictionary中强制转换的Any对象(类型取决于您接收的数据)。

例如:

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

如果你有多种数据,你应该使用这个数据:

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

然后,您可以通过密钥访问字典中的所有数据并管理数据(如果使用Any,请记住在使用之前输入正确的数据)。

这里有一些文档:https://developer.apple.com/documentation/foundation/jsonserialization

Swift 4之后

使用Swift 4引入了一个新类:JSONEncoder和JSONDecoder。 这太棒了,因为你可以创建你的模型,解析json,你会得到一个已填充所有字段的对象。 注意你的模型必须实现协议Codable(或Encodable和Decodable)。如果您的模型没有实现协议,您将收到错误。

这是一个例子:

这是我的模特:

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

这是解析的代码:

let decoder = JSONDecoder()

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

现在我的变量“myClass”已经包含了json中填充数据的所有字段。

这里有一些文档:

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

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

答案 1 :(得分:0)

尝试

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!)
}
}

当我以JSON形式发帖时,请告知我任何更正