Swift 4 – 使用Codable协议进行JSON解析(嵌套数据)

我正在尝试更新自己并使用现代和最新的Swift 4function。

这就是我使用Codable协议进行训练以解析JSON并直接映射我的模型对象的原因。

首先,我做了一些研究和自学。

这篇文章给了我很多帮助: 终极指南

我只需要关注“Com”数组。

您可以注意到,它包含一些嵌套对象。 我将它们命名为Flash Info。

它的定义是:

  • 结束日期
  • 文本
  • 图片[]
  • 标题
  • 生产日期
  • ID

所以这是我的Codable Struct:

 struct FlashInfo : Codable { let productionDate: String let endDate: String let text: String let title: String let id: String } 

首先,我试图在没有图像数组的情况下解析它,我稍后会处理它。

所以这是我的方法:

 func getFlashInfo(success: @escaping (Array) -> Void) { var arrayFlash = [FlashInfo]() Alamofire.request(URL_TEST, method: .get).responseJSON { response in if response.value != nil { if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) { print("Data: \(utf8Text)") } //let decoder = JSONDecoder() // let flash = try! decoder.decode(FlashInfo.self, from: response.data!) // arrayFlash.append(flash) success(arrayFlash) } else { print("error getFlashInfo") } } } 

我不知道如何处理这样一个事实:我只需要“Com”数组以及如何迭代所有嵌套对象以便在回调中填充我的数组。

我的意思是,解码协议会迭代每个对象吗?

我清楚了吗?

编辑:JSON作为文本

 {"Test": [], "Toto": [], "Com": [{"endDate": "2017-06-27T08:00:00Z", "text": "John Snow is getting married", "image": ["895745-test.png", "632568-test.png"], "titre": "We need you!", "productionDate": "2017-07-02T16:16:23Z", "id": "9686"}, {"endDate": "2017-07-27T08:00:00Z", "text": "LOL TEST", "image": ["895545-test.png", "632568-test.png"], "titre": "She needs you!", "productionDate": "2017-08-02T16:16:23Z", "id": "9687"},{"endDate": "2017-06-27T08:00:00Z", "text": "iOS swift", "image": ["895775-test.png", "638568-test.png"], "titre": "They need you!", "productionDate": "2017-07-02T16:16:23Z", "id": "9688"}], "Yt": []} 

我相信最快的方法就是定义一个不完整的 Response类型。 例如:

 struct Response: Codable { let Com: [FlashInfo] } struct FlashInfo: Codable { let productionDate: String let endDate: String let text: String let title: String let id: String let image: [String] = [] // Ignored for now. enum CodingKeys: String, CodingKey { case productionDate, endDate, text, id case title = "titre" // Fix for JSON typo ;) } } 

并解码它像这样:

 let decoder = JSONDecoder() let response = try! decoder.decode(Response.self, from: data) print(response.Com) 

这对您提供的测试数据非常有用 (只需注意title字段中的拼写错误 ):

 let json = """ {"Test": [], "Toto": [], "Com": [{"endDate": "2017-06-27T08:00:00Z", "text": "John Snow is getting married", "image": ["895745-test.png", "632568-test.png"], "titre": "We need you!", "productionDate": "2017-07-02T16:16:23Z", "id": "9686"}, {"endDate": "2017-07-27T08:00:00Z", "text": "LOL TEST", "image": ["895545-test.png", "632568-test.png"], "titre": "She needs you!", "productionDate": "2017-08-02T16:16:23Z", "id": "9687"},{"endDate": "2017-06-27T08:00:00Z", "text": "iOS swift", "image": ["895775-test.png", "638568-test.png"], "titre": "They need you!", "productionDate": "2017-07-02T16:16:23Z", "id": "9688"}], "Yt": []} """ let data = json.data(using: .utf8)!