Skip to content

Instantly share code, notes, and snippets.

@mnem
Created August 30, 2017 18:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mnem/29ded00b170055525ab1ff29a53aa2f6 to your computer and use it in GitHub Desktop.
Save mnem/29ded00b170055525ab1ff29a53aa2f6 to your computer and use it in GitHub Desktop.
Decoding values from silly heterogenous JSON arrays.
//: Playground - noun: a place where people can play
import Foundation
let json = """
[
{"person":{"name":"foo", "age":20}},
{"house":{"size":"large"}}
]
""".data(using: .utf8)!
struct Person: Decodable {
let name: String
let age: Int
}
struct House: Decodable {
let size: String
}
struct Heterogenous: Decodable {
let person: Person
let house: House
enum ItemKeys: String, CodingKey {
case person
case house
}
init(from decoder: Decoder) throws {
var values = try decoder.unkeyedContainer()
person = try values.nestedContainer(keyedBy: ItemKeys.self).decode(Person.self, forKey: .person)
house = try values.nestedContainer(keyedBy: ItemKeys.self).decode(House.self, forKey: .house)
}
}
let decoder = JSONDecoder()
do {
let things = try decoder.decode(Heterogenous.self, from: json)
dump(things)
} catch {
dump(error)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment