ios - Swift 4 - 使用 Codable 协议(protocol)解析 JSON(嵌套数据)

标签 ios json swift decode swift4

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

这就是为什么我使用 Codable 协议(protocol)进行训练以解析 JSON 并直接映射我的模型对象。

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

这篇文章对我帮助很大:Ultimate guide

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

如您所见,它包含一些嵌套对象。我将它们命名为 Flash Info。

它的定义是:

  • 结束日期
  • 正文
  • 图片[]
  • 标题
  • 生产日期
  • 编号

这是我的 Codable 结构:

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”数组这一事实以及如何遍历所有嵌套对象以便在回调中填充我的数组。

我的意思是,解码协议(protocol)会遍历每个对象吗?

我清楚了吗?

编辑: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)!

关于ios - Swift 4 - 使用 Codable 协议(protocol)解析 JSON(嵌套数据),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46935354/

相关文章:

iOS 通过 iPhone 听筒(手机喇叭)播放音频

iphone - 以编程方式在 iPhone 中绘制 View : What to do for iPad Version

iphone - 在以编程方式填充的 TableView 中不刷新屏幕

javascript - Angular-nvD3 条形图 y 轴缩放错误(AngularJS)

ios - 如何以编程方式在 iPhone 中强制选择 2G 或 3G?

ios - 通过数组添加的 View 的约束

php - 错误的 json 数组 Python post 请求到 PHP

java - 解析 Android Volley JSONArray 响应

ios - 异步加载的 UICollectionView 速度慢

ios - 在swift中使用字典的不同数据类型?