Swift Codability

Written by ravi.aggarwal61 | Published 2017/07/09
Tech Story Tags: codable | json | encoding-decoding | swift-4 | json-mapping

TLDRvia the TL;DR App

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 Encodable & Decodable. So, if you only want to encode or decode, you can just adopt the appropriate protocol.

But, Codable comes with default implementation and you can adopt this protocol to get 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 CodingKeys enumeration which conforms to CodingKey protocol. It defines how we can connect a property to a value.

So, to customise the key, we’ll have to write our own implementation of CodingKeys and there we can provide String values for keys that you want to change.

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 CodingKeys enum as a lookup and matches the corresponding JSON keys to Model variables.

Also, since String enums are implicitly assigned raw values as each case’s name, we only need to provide raw values for problematic cases.

But wait, what about Objects or Wrappers?

Objects and Wrappers

Let’s assume our JSON is

Here, you have to make sure your Film object also conforms to Codable and that’s basically it. Here, have a looksee.

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 String and converted to a Date using DateFormatter. Ugh! I Know!!

The good news is, now you can decode the date string from JSON right into the model using JSONDecoder. Checkity check it

Same goes for Encoder too. Apart from these strategies, you can even use custom encoder and decoder

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 Data in your JSON as base64 encoded strings and to handle this JSONEncoder gives these two strategies

.base64.custom((Data, Encoder) throws -> Void)

Same goes for JSONDecoder too.

When it comes to URL, just replace the data type from String to URL and that’s it

Handling Floating Point??

Well, this doesn’t happen often but sometimes JSON might contain an invalid “NaN”, “+Infinity” or “-Infinity”. These are not recognised in Swift!

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 JSONEncoder as well.

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 Encodable or Decodable and work from there. But, before that, we need to understand the concept of containers. These are some types of containers:

  • Keyed Container: This is essentially a dictionary type and contains key-value pairs.
  • Unkeyed Container: represents a wrapper, essentially an array.
  • Single Value Container: represents a raw type denoted by a key.

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 or we can do this:

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 "film" object to the filmInfo container and then use it to decode values in movieName and director keys.

Similarly, for Encoder, we take our movieName and director keys and encode them in the filmInfo container and this will return the exact JSON as before. That’s the power of coding keys.

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 "Death Star" & "Millennium Falcon" nests a model inside. Let’s see what we can make of this

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 catch as a panacea, but there are some known cases that we can catch and handle accordingly.

  1. DecodingError.dataCorrupted(DecodingError.Context): 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 context.
  2. DecodingError.keyNotFound(CodingKey, DecodingError.Context): This occurs if a required key is not found in JSON, CodingKey will give you the problematic key and context will give you information about where and what happened.
  3. DecodingError.typeMismatch(Any.Type, DecodingError.Context): This occurs if there is a type mismatch between the keys. You can use the context and type to know what happened.

Have a look

Same goes for Encoder, these errors are very helpful in giving you the flexibility to adapt to certain situations and handle them appropriately.

Further Learning

There is nothing better than the WWDC 2017 resource themselves. Here…

What's New in Foundation - WWDC 2017 - Videos - Apple Developer_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

Using JSON with Custom Types | Apple Developer Documentation_JSON data you send or receive from other apps, services, and files can come in many different shapes and structures…_developer.apple.com

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


Published by HackerNoon on 2017/07/09