Reputation: 440
I am trying to decode some JSON. Here is an example of the 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.
]
It begins as an unkeyed array. This is then follewed by JSON containers that are also unkeyed. I am having trouble breaking it apart using this code:
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
}
}
}
Im new to JSON and Swift Decodable so I am a bit confused what I am doing wrong? Does anyone know how I can fix my issue? Right now I am getting the warning that it is expecting an array but it is finding a dictionary. Therefore, I think I have successfully gotten past the first unkeyed container but I cant get into the rest of it.
Upvotes: 1
Views: 2203
Reputation: 51972
Remove your init method and then do
let decoder = JSONDecoder()
do {
data = try decoder.decode([FlightData].self, from: data)
} catch {
print(error)
}
Upvotes: 3