JSON Parsing with Decodable — A Swift Love Story
Which app does not parse JSON data these days(Firebase based apps maybe).
Decoding a JSON response can get pretty intense with all the unwrapping and error handling. Thanks to the Decodable protocol, Swift has made a developers most common task as easy as a few lines.
A type that can decode itself from an external representation — Apple
One can parse any data from a JSON Object or Property List to a conformingStruct
orClass
, without any incovernience.
Pros
- Decodable is standard, so more people will know how to use them and it will catch on
- has some nice enum usage which helps code readability
- lesser code
- lesser time spent writing and modifying code
- error handling done by the catch block when decoding the data(JSON or any other property list)
Cons
- You could achive all of what these new features offer with reflection.
- Must implement another required init for all subclasses
- Support only with Swift 4 and onwards
In my opinion the pros outweigh the cons and Decodable is an easy winner.
I recommend using it a lot.
And now for the most important bit, how to use it!
This is when you have a simple JSON, the variable names are equal to the keys of the JSON data.
What if your keys and variable names need to differ, maybe because you use camel case (helloWorld) instead of kebab case(hello_world).
Decodable has the solution for that too!
Check out the CodingKeys, where the enums are the keys in the JSON data. If your variable and the corresponding key do not match, specify the String corresponding the the respective enum.
For more information on Decodable, visit the following:
- By Apple [26th Minute] : https://developer.apple.com/videos/play/wwdc2017/212
- By KiloLoco : https://www.youtube.com/watch?v=P6NEUpLhpUM
- By Lets build that app: https://www.youtube.com/watch?v=YY3bTxgxWss
Conclusion
Give it a try and I assure you, you will not want to rely or use unncessary libraries and code for the very basic JSON parsing.
Happy Learning!