Decode JSON Like A PRO
Difficulty: Beginner | Easy | Normal | Challenging
This article has been developed using Xcode 11.5, and Swift 5.2.4
If you prefer a video for this content, here that your option!
- You will be expected to be aware how to make a Single View Application in Swift.
- This article is a continuation of an existing article about codable with nested JSON
Decoding JSON is good, right?
I remember creating an article about Using Codable with Nested JSON and we can easily test JSON decoding yet it is missing a vital part of deciding JSON — one that is very likely to come up in your daily life as a developer (really).
JSON arrays are common in JSON strings from any given API endpoints.
Now this particular article will talk about decoding JSON with nested arrays, and will not venture into testing since that would be a re-tread of this article.
An example situation
Imagine (if you’ve a reasonable imagination that is, but don’t get too excited) that you’ve logged into an API. Since the App in question is something like a social network, you are returned your user’s first name, second name and some information about their friends on the network.
Naturally you’d need to put this into a model that you call from your ViewModels (you’re using MVVM, right?) — but it’s an *array* of friends. So you don’t know how many friends you have in advance (it might even be zero — but we can talk about my problems later).
The JSON String
This is an *example* JSON String, but should give you some idea of what we are working with.