Swift 4-使用Codable协议进行JSON解析(嵌套数据) [英] Swift 4 - JSON parsing with Codable protocol (nested data)

查看:185
本文介绍了Swift 4-使用Codable协议进行JSON解析(嵌套数据)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to update myself and use modern and recent Swift 4 features.

这就是为什么我要使用 Codable进行培训

That is why I am training with the Codable protocol in order to parse JSON and directly map my model object.

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

First of all, I did some research and self learning.

这篇文章对我有很大帮助:最终指南

This article helped me a lot : Ultimate guide

我只需要关注 Com数组。

I just need to focus on the "Com" array.

您会注意到,它包含一些嵌套对象。我将它们命名为Flash信息。

As you can notice, it contains some nested object. I named them Flash Info.

它的定义是:


  • endDate

  • 文本

  • 图像[]

  • 标题

  • productionDate

  • id

  • endDate
  • text
  • image[]
  • title
  • productionDate
  • id

这是我的可编码结构:

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.

所以这是我的方法:

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数组的事实,以及如何遍历所有嵌套对象以将数组填充到回调中。

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.

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

I mean, will the decode protocol iterate through each objects ?

我知道吗?

编辑:JSON作为文本

JSON as text

{"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": []}


推荐答案

我相信最快的方法就是定义 incomplete 响应类型。例如:

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

并像这样解码:

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

这非常适合您提供的测试数据(只需注意 title 字段中的 typo ):

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)!

这篇关于Swift 4-使用Codable协议进行JSON解析(嵌套数据)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆