JSON/[String: Any] Support for Codable

Mastering Codables in Swift

Satyenkumar Mourya
2 min readMay 9, 2021

Many a time we all have faced a problem with Codable for a little bit more flexibility, for some uncertain data as you know Codables doesn't support [String: Any] data type for their properties. This is the issue that will get addressed here.

So when I searched for this particular topic I easily got extensions for supporting Decodable from many sources I have combined all those sources and improved a little for more robust support.

What I didn’t get was encoding the [String: Any]/[Any] properties hence I wrote an extension for supporting those, that made a proper working solution.

You will have to write a custom decoder and encoder but I think that’s a price you have to pay for a little flexibility 😜.

“Any” here is any primitive data type such as String, Bool, Int, Double, Float, and also recursive [String: Any]. Also, there are some extra extensions added to make your life easier, feel free to explore.

You will be easily able to decode & encode data such as:

Sample JSON

All you need to decode the above data is:

Code to decode the sample JSON

Now that we know what we will be achieving let's see the extensions responsible for it.

If you like what you see you can follow me on LinkedIn, Github, and Medium.

Sources:
StackOverflow thread for decodable support

--

--

Satyenkumar Mourya
Satyenkumar Mourya

Written by Satyenkumar Mourya

iOS Developer | Fullstack Developer | Coder

No responses yet