[英]Swift 4 - JSON parsing with Codable protocol (nested data)
I am trying to update myself and use modern and recent Swift 4 features. 我正在尝试更新自己并使用现代和最新的Swift 4功能。
That is why I am training with the Codable
protocol in order to parse JSON and directly map my model object. 这就是我使用
Codable
协议进行训练以解析JSON并直接映射我的模型对象的原因。
First of all, I did some research and self learning. 首先,我做了一些研究和自学。
This article helped me a lot : Ultimate guide 这篇文章给了我很多帮助: 终极指南
I just need to focus on the "Com" array. 我只需要关注“Com”数组。
As you can notice, it contains some nested object. 您可以注意到,它包含一些嵌套对象。 I named them Flash Info.
我把它们命名为Flash Info。
It is defined by : 它的定义是:
So here is my Codable Struct : 所以这是我的Codable Struct:
struct FlashInfo : Codable {
let productionDate: String
let endDate: String
let text: String
let title: String
let id: String
}
First of all, I was trying to parse it without the array of Images, I will handle it later. 首先,我试图在没有图像数组的情况下解析它,我稍后会处理它。
So here is my method : 所以这是我的方法:
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")
}
}
}
I don't know how to handle the fact that I only need the "Com" array and how to iterate through all nested objects in order to fill my array in the callback. 我不知道如何处理这样一个事实:我只需要“Com”数组以及如何迭代所有嵌套对象以便在回调中填充我的数组。
I mean, will the decode protocol iterate through each objects ? 我的意思是,解码协议会迭代每个对象吗?
Am I clear? 我清楚了吗?
EDIT: JSON as text 编辑: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": []}
I believe the quickest way is just to define an incomplete Response
type as well. 我相信最快的方法就是定义一个不完整的
Response
类型。 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): 这对您提供的测试数据非常有用 (只需注意
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)!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.