Swift 4: JSON decoding with JSONDecoder() and structs

I have no apps in the app store, but a while ago I wrote an app for my own edutainment, which needed to parse JSON Data. At the time it was so darn complicated, that I enlisted Cocoapods and SwiftyJSON to help make things easier. SwiftJSON is pretty cool as it abstracts away a lot of complexity, but Apple has since come a long way in making JSON handling much easier.

So let’s assume that this is my JSON:

{
  "msg": 200,
  "data": [
    {
      "Aircraft": "B738",
      "Registration": "TC-SED",
      "Origin": "FRA",
      "Destination": "ADB",
      "Timestamp": "1537623989",
      "FlightNumber": "XQ971"
    },
    {
      "Aircraft": "B738",
      "Registration": "TC-SOG",
      "Origin": "FRA",
      "Destination": "AYT",
      "Timestamp": "1537623838",
      "FlightNumber": "XQ143"
    }
  ]
}

In order to parse this with the Swift-Native way, I would create two “decodable structs” as follows

struct PlaneFeed : Decodable {
    let msg : Int
    let data : [PlaneEntry]
}
    
struct PlaneEntry : Decodable {
    let Aircraft : String
    let Registration : String
    let Origin : String
    let Destination : String
    let Timestamp : String
    let FlightNumber : String
}

This really isn’t so hard, right? You basically just reconstruct the JSON structure – and yes I really dislike the uppercase keys used in that JSON. Anyhow, to decode this now, it will be as simple as doing the following – data is the result URLSession…

let planeData = try JSONDecoder().decode(PlaneFeed.self, from: data)

Yup, that is it. You basically told the system in a single line that these planeData Objects can be constructed by looking at the structure for PlaneFeed and PlaneFeed references PlaneEntry and there you are. If you needed iterate through each response, you could now do the following:

for plane in planeData.data{
  //access your data with the keys from the struct
}

I rarely get excited by Apple Developer Documentation. I am simply not good enough of a developer to fully understand it and without a good example I am lost. However this is one of the areas, where Apple really provided a good bit of “Claus-Friendly” Documentation – learn more at https://developer.apple.com/documentation/foundation/jsondecoder

 

Swift 4: JSON decoding with JSONDecoder() and structs
Scroll to top