Created
November 23, 2018 10:16
-
-
Save westerlund/1fc0c02ba9a9131a83692400a2476ccb to your computer and use it in GitHub Desktop.
This file contains 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
let json = """ | |
{ | |
"foo": "bar", | |
"baz": null | |
} | |
""" | |
struct Type: Decodable { | |
let type: String | |
let value: String? | |
} | |
struct Response: Decodable { | |
let types: [Type] | |
init(from decoder: Decoder) throws { | |
let container = try decoder.singleValueContainer() | |
let dict = try container.decode([String: String?].self) | |
types = try dict.map { element in | |
let dict = ["type": element.key, "value": element.value] | |
let data = try JSONEncoder().encode(dict) | |
return try JSONDecoder().decode(Type.self, from: data) | |
} | |
} | |
} | |
let data = json.data(using: .utf8)! | |
do { | |
let response = try JSONDecoder().decode(Response.self, from: data) | |
print(response) | |
} catch { | |
print(error) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment