Decoding Heterogeneous JSON
Handle polymorphic and dynamic JSON shapes.
What Is Heterogeneous JSON?
Some APIs return arrays where objects have different shapes, distinguished by a type field. Decoding these into one Swift type requires inspecting that discriminator first.
import Foundation
let json = "[{\"type\":\"text\",\"value\":\"hi\"},{\"type\":\"number\",\"value\":42}]"
print("Each element carries a type discriminator")Modeling with an Enum
A natural Swift model is an enum with associated values — one case per JSON shape. The decoder will pick the case based on the discriminator.
import Foundation
enum Block {
case text(String)
case number(Int)
}
print("Enum models the variants")All lessons in this course
- CodingKeys for Renaming
- Key and Date Decoding Strategies
- Manual encode(to:) and init(from:)
- Decoding Heterogeneous JSON