0Pricing
Swift Academy · Lesson

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

  1. CodingKeys for Renaming
  2. Key and Date Decoding Strategies
  3. Manual encode(to:) and init(from:)
  4. Decoding Heterogeneous JSON
← Back to Swift Academy