Swift 4 - JSON parsing with Codable protocol (nested data)

丶灬走出姿态 提交于 2019-12-06 22:11:28

I believe the quickest way is just to define an incomplete Response type as well. For instance:

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

and decode it like this:

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

This worked great with the test data you provided (just watch out for the typo in the title field):

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)!
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!