Skip to main content
100%

Decode JSON with Dynamic Keys using Decodable

✓ Published0🌍 Public
KKevinGutowski
Last edited Dec 23, 2020
Created on Dec 23, 2020

This example demonstrates how to decode a JSON object with dynamic keys using Swift’s `Decodable` protocol, mapping student IDs like "S001" to an array of `Student` objects. The `School` struct implements a custom `init(from:)` decoder, which uses a `nestedContainer(keyedBy: GenericCodingKeys.self)` to iterate over all keys in the "students" dictionary and decode each entry. `GenericCodingKeys` is a custom `CodingKey` type that accepts any string value, while Foundation’s `JSONDecoder` parses the embedded sample JSON data. The code prints the first decoded student after processing.

AI-generated description

Similar vizzes