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:

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

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…

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:

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

 

You Might Also Like