JSON/[String: Any] Support for Codable
Mastering Codables in Swift
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:
All you need to decode the above data is:
You can view the sample project and all the goodies on this Github repo.
Now that we know what we will be achieving let's see the extensions responsible for it.