无密钥容器JSON Swift可解码

时间:2019-05-27 15:23:28

标签: json swift decodable

我正在尝试解码一些JSON。这是JSON的示例:

 [
    {
        "type": "departure",
        "status": "landed",
        "departure": {
            "iataCode": "JFK",
            "icaoCode": "KJFK",
            "scheduledTime": "2017-12-11T01:06:00.000",
            "estimatedRunway": "2017-12-11T02:07:00.000",
            "actualRunway": "2017-12-11T02:07:00.000" },
        "arrival": {
            "iataCode": "CVG",
            "icaoCode": "KCVG",
            "estimatedRunway": "2017-12-11T03:38:00.000",
            "actualRunway": "2017-12-11T03:38:00.000"
        },
        "airline": {
            "name": "Atlas Air",
            "iataCode": "5Y",
            "icaoCode": "GTI"
        },
        "flight": {
            "number": "302",
            "iataNumber": "5Y302",
            "icaoNumber": "GTI302"
        }
    }, 
    {

        //Same keys as above.
    }, 
    //Etc.
]

它以无键数组开始。然后,这也由同样未设置密钥的JSON容器禁止。我无法使用以下代码将其拆分:

struct Dataset: Decodable {

    var data: [FlightData]

    init(from decoder: Decoder) throws {
        var container = try decoder.unkeyedContainer()
        print(container)
        data = [try container.decode(FlightData.self)]
    }

struct FlightData: Decodable {

    var type: String //Arrival or Departure
    var status: String //Flight Status

    var departure: Departure
    var arrival: Arrival
    var airline: Airline
    var flight: Flight

    struct Departure: Decodable {

        var iataCode: String
        var icaoCode: String
        var terminal: String
        var gate: String
        var scheduledTime: String
        var estimatedTime: String
        var actualTime: String
        var estimatedRunway: String
        var actualRunway: String

    }

    struct Arrival: Decodable {

        var iataCode: String
        var icaoCode: String
        var terminal: String
        var gate: String
        var baggage: String
        var scheduledTime: String
        var estimatedTime: String
        var actualTime: String
        var estimatedRunway: String
        var actualRunway: String

    }

    struct Airline: Decodable {

        var name: String
        var iataCode: String
        var icaoCode: String

    }

    struct Flight: Decodable {

        var number: String
        var iataNumber: String
        var icaoNumber: String

    }

}
}

我是JSON和Swift Decodable的新手,所以我有点困惑我做错了什么? 有谁知道我该如何解决我的问题? 现在,我收到警告,它期望使用数组,但正在查找字典。因此,我认为我已经成功地通过了第一个未加锁的容器,但我无法进入其余的容器。

1 个答案:

答案 0 :(得分:1)

删除您的init方法,然后执行

let decoder = JSONDecoder()

do {
    data = try decoder.decode([FlightData].self, from: data) 
} catch {
    print(error)
}