Using Codable with Nested JSON? You Can!

Nesting? Don’t worry!

Steven Curtis

--

Photo by Rana Sawalha on Unsplash

Still using several structs to decode data that is in a nested JSON String? Well, no longer! This article is here to help you out.

Do note that following this article involves testing from the Playground and using Codable

Difficulty: Beginner | Easy | Normal | Challenging

The JSON String

The following JSON response is meant to represent a user. Now this is a common construct, and as we can see has a nested name within the jsonString.

Click for Gist

The poor solution

A common (but poor) solution for this is to produce objects of type struct and decode. The separate objects are…not ideal:

Click for Gist

This can then be tested (of course if you are following along in a Playground you’ll need to import XCTest and also JSONTests.defaultTestSuite.run())

--

--