Skip to content

Category: JSON

Restoring your sanity reading JSON into Codables

Integrating your app with APIs means you’re going to be dealing with parsing JSON in data objects you can use nicely. iOS provides the Codable protocol to do just that thing, but once you start trying to map JSON to that well-formed protocol, that’s when things fall apart.

JSON doesn’t have standard schemas (at least none that were ever seriously adopted), so you’re stuck with reading documentation like this for the details:

😒 Great, that’s useful… One example response, no field descriptions, types, anything. (And before you ask, this is the GitHub API documentation, so not even large organizations are immune to this problem.)

So you code your app off of these examples, then when you try and use it in the wild, you get:

I followed their documentation, and it didn’t work. How the heck am I ever going to figure out how to make this API JSON into a nice, easy to use Swift struct?!

Thankfully, there are some tricks — and one tool — you can use to make your job a lot easier. We’ll start by deciphering those error messages above, and how to figure out what error they are trying to point out. Then we’ll cover a procedure I like to use whenever I encounter one of these errors to fix them, and even use to avoid these errors in the first place. Let’s dive in.