Easy JSON Parsing with Swift Codable
There has been a number of great libraries for parsing, but it is quite refreshing to see a fully-supported solution that is easy to adopt . Swift 4 finally answered the solution to parse JSON with new Codable protocol.
If your JSON structure and objects have similar structure, then just adopt this protocol and get useful default behavior for free. Codable is a protocol composition type, consisting of Encodable & Decodable.
Here’s an example for a User:
Let call a simple API which gives JSON data,
Now its time to parse data. Just create JSONDecoder and use decode method as given below
And that’s it! We’ve parsed our JSON document into a User instance. It didn’t require any customization since the key names and types matched each other.
We’re using try! for the sake of an example, but in your app you should catch any errors and handle them intelligently.
I will suggest you to watch the related WWDC session(the Codablepart starts past 23 minutes).