Ever tried to parse JSON in swift? I know! right, the sheer magnitude of boilerplate with so many nil checks makes it a really bad experience. I am here to provide you a solution to this problem with the newly introduced Swift 4, with it Apple has finally answered the question of parsing JSON painlessly. Let’s start with the basics Let’s take a basic JSON structure Our swift mapping model will look something like this: And to convert this JSON data to our model, this is literally all the code that we have to write You can encode this model to JSON as well Great!! isn’t it? I have marked the Person model as Codable, which is a combination of two unidirectional protocols . So, if you only want to encode or decode, you can just adopt the appropriate protocol. Encodable & Decodable But, comes with default implementation and you can adopt this protocol to get Codable free implementation. There’s a catch! Name of the variable in your model should match the key name in JSON. Whaaaat… Life’s not fair, most APIs are based on snake case naming 😢. Well, relax… Working with customised key names Key names are automatically generated by the compiler in a enumeration which conforms to protocol. It defines how we can connect a property to a value. CodingKeys CodingKey So, to customise the key, we’ll have to write our own implementation of and there we can provide values for keys that you want to change. CodingKeys String Let’s take an example, consider this JSON Here’s how our model will look like Well, that’s it 👍🏻 Swift Encoder & Decoder use this enum as a lookup and matches the corresponding JSON keys to Model variables. CodingKeys Also, since enums are implicitly assigned raw values as each case’s name, we only need to provide raw values for problematic cases. String But wait, what about Objects or Wrappers? Objects and Wrappers Let’s assume our JSON is Here, you have to make sure your object also conforms to and that’s basically it. Here, have a looksee. Film Codable What about root level arrays? Any easy way to decode if our JSON comes wrapped in an array. Well, ¯\_(ツ)_/¯ take this JSON for instance. All you have to write is this, 😬 How to handle Dates? Well, get your life together ^.~ In swift though, Since JSON has no data type to represent dates, that information is serialised in either ISO 8601, the number of seconds from reference date or some custom format. It was then handled using and converted to a using DateFormatter. Ugh! I Know!! String Date The good news is, now you can decode the date string from JSON right into the model using . Checkity check it JSONDecoder Same goes for too. Apart from these strategies, you can even use custom encoder and decoder Encoder custom((Decoder) throws -> Date) //For Decodingcustom((Date, Encoder) throws -> Void) //For Encoding I know, I know, an example would be good. Here Handling Swift.Data and URL!! You might encounter in your JSON as base64 encoded strings and to handle this gives these two strategies Data JSONEncoder .base64.custom((Data, Encoder) throws -> Void) Same goes for too. JSONDecoder When it comes to , just replace the data type from to and that’s it URL String URL Handling Floating Point?? Well, this doesn’t happen often but sometimes JSON might contain an invalid . These are not recognised in Swift! “NaN”, “+Infinity” or “-Infinity” Normally your decoder will throw an error if you do not provide an implementation to handle this non-conformity. Just write Similarly, this can be done with as well. JSONEncoder Wait, but what about unidirectional conformance? There is no default implementation for that! I’ll show you, it’s really cool Unidirectional Encodable & Decodable Sometimes you might just want to conform to either or and work from there. But, before that, we need to understand the concept of containers. These are some types of containers: Encodable Decodable This is essentially a dictionary type and contains key-value pairs. Keyed Container: represents a wrapper, essentially an array. Unkeyed Container: represents a raw type denoted by a key. Single Value Container: Now, all you have to do is guide the compiler how you want the data to be decoded and that’s it. Have a look Let’s assume we have the following JSON, now we can make a nested model we can do this: or Since movie name and director name comes nested in a container, we can use the nested container property of decoder to extract the values and use in corresponding keys. Here, I am extracting the object to the container and then use it to decode values in and keys. "film" filmInfo movieName director Similarly, for , we take our and keys and encode them in the container and this will return the exact JSON as before. That’s the power of coding keys. Encoder movieName director filmInfo Handle dictionary and enum? You won’t need this as often but you can parse your JSON in a dictionary or an enumeration too. Dictionary Consider the following JSON Can you identify any similarity between these objects? Both nests a model inside. Let’s see what we can make of this "Death Star" & "Millennium Falcon" Enumerations Let’s take in a straight dive with this JSON Yeah! that’s one weird JSON, but it’ll do the trick. Let’s have a look at our code Congrats! You have successfully parsed your JSON to enum cases. There are some errors to be handled :) Till now, all we used was a simple as a panacea, but there are some known cases that we can catch and handle accordingly. catch This could occur if the data you received is not JSON, maybe an HTML or an API error. You will get this information using the . DecodingError.dataCorrupted(DecodingError.Context): context This occurs if a required key is not found in JSON, will give you the problematic key and will give you information about where and what happened. DecodingError.keyNotFound(CodingKey, DecodingError.Context): CodingKey context This occurs if there is a type mismatch between the keys. You can use the and to know what happened. DecodingError.typeMismatch(Any.Type, DecodingError.Context): context type Have a look Same goes for , these errors are very helpful in giving you the flexibility to adapt to certain situations and handle them appropriately. Encoder Further Learning There is nothing better than the WWDC 2017 resource themselves. Here… _Whether you're building apps for iOS, macOS, watchOS, or tvOS, a lot of the functionality you get from Apple's SDKs…_developer.apple.com What's New in Foundation - WWDC 2017 - Videos - Apple Developer _JSON data you send or receive from other apps, services, and files can come in many different shapes and structures…_developer.apple.com Using JSON with Custom Types | Apple Developer Documentation Conclusion Whoot! This was a looong ride, but this is the future of Swift JSON parsing. Comments/Suggestions are welcome :) (-ω-ゞ Adiós May the force be with you