簡體   English   中英

Swift 4 - 使用Codable協議進行JSON解析(嵌套數據)

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

我正在嘗試更新自己並使用現代和最新的Swift 4功能。

這就是我使用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<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")
            }
        }
    }

我不知道如何處理這樣一個事實:我只需要“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)!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM