Skip to content

Instantly share code, notes, and snippets.

@westerlund
Created November 23, 2018 10:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save westerlund/1fc0c02ba9a9131a83692400a2476ccb to your computer and use it in GitHub Desktop.
Save westerlund/1fc0c02ba9a9131a83692400a2476ccb to your computer and use it in GitHub Desktop.
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