How to Decode This JSON Using Swift Decodable

Decode and Flatten JSON with Dynamic Keys

Lee Kah Seng
The Startup

--

This article is originally published at https://swiftsenpai.com on May 30, 2020.

The Decodable protocol was introduced in Swift 4. Since then it has become the standard way for developers to decode JSON received from a remote server.

There are tons of tutorials out there that teach you how to utilize the Decodable protocol to decode various types of JSON structure. However, all these tutorials do not cover one specific type of JSON structure - JSON with dynamic keys.

What do I mean by JSON with dynamic keys? Take a look at the following sample JSON that shows a list of students:

As you can see, the student ID is the key and the student information is the value.

As iOS developers, what we usually need is an array of students, so that the list of students can be easily displayed on a table view. Therefore, aside from decoding the JSON, we also need to flatten the result (make student ID part of the student…

--

--

Lee Kah Seng
The Startup

Support me by becoming a Medium member: https://leekahseng.medium.com/membership ⦿ 🇲🇾 Creator of https://swiftsenpai.com ⦿ iOS developer since 2011