JSON Encoding And Decoding - Swift 5
Short and detailed introduction in JSON encoding and decoding in Swift 4

Swift 4 gives us a new and much easier way to work with JSON. Let’s imagine that we create an app where we work with users profiles. And after a .get request we received a person. Let’s create its struct:
Now we may create an instance of our Struct and print its data just to make sure that it’s our correct instance:
If we need to represent our person instance as a Data in Swift 4 we may do it in a single line:
Imagine, that you have to send this instance on a server in a JSON representation, if you have your instance firstly you have to convert it in Data type and then you may create a JSON:
if you received a person as a JSON and you need to convert it to a struct instance firstly you have to convert it in Data and then you may convert it in a struct :
This code above doesn’t look very readable but I wanted to show you the exact flow of steps and you can easily see it in the gist above.
Nested Types
What is amazing in Swift 4 that decoding and encoding of nested types have no difference and completely the same as the sample above. Using the Person structure above let’s create a new struct Family with the struct Person as a nested type that also conforms to a Codable protocol:
As with the sample above if we want to represent our Family as a JSON we have to convert it to Data and then to JSON:
And if we want to convert our Family JSON back to struct we have to convert it in a Data and then back in a struct :
Conclusion
As we see it’s very easy to work even with complicated models in Swift 4. You may easily encode and decode different not common structs and classes with nested types.
Thanks for your time and hope this writing was useful for you. Please don’t forget to 💚 if you found this article useful.
Thanks for reading! 🚀
