Created
August 30, 2017 18:43
-
-
Save mnem/29ded00b170055525ab1ff29a53aa2f6 to your computer and use it in GitHub Desktop.
Decoding values from silly heterogenous JSON arrays.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//: 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