我正在尝试更新自己并使用现代和最新的Swift 4功能。
这就是我使用Codable
协议进行训练以解析JSON并直接映射我的模型对象的原因。
首先,我做了一些研究和自学。
这篇文章给了我很多帮助:Ultimate guide
我只需要专注于" Com"阵列。
您可以注意到,它包含一些嵌套对象。我将它们命名为Flash Info。
定义如下:
所以这是我的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<FlashInfo>) -> 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")
}
}
}
我不知道如何处理我只需要&#34; Com&#34;数组以及如何迭代所有嵌套对象以便在回调中填充我的数组。
我的意思是,解码协议会遍历每个对象吗?
我清楚了吗?
编辑: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": []}
答案 0 :(得分:3)
我认为最快的方法就是定义一个不完整的 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)!