Using Codable with Nested JSON? You Can!
Nesting? Don’t worry!
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
.
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:
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()
)