Skip to content

Instantly share code, notes, and snippets.

@JarvisTheAvenger
Created April 19, 2019 08:46
Show Gist options
  • Save JarvisTheAvenger/b5a47a8d8b88a8f45e861d6064bdadb8 to your computer and use it in GitHub Desktop.
Save JarvisTheAvenger/b5a47a8d8b88a8f45e861d6064bdadb8 to your computer and use it in GitHub Desktop.
import Foundation
let json = """
[
{
"name": {
"firstName": "Taylor",
"lastName": "Swift"
},
"age": 26
}
]
"""
struct User: Decodable {
var firstName: String
var lastName: String
var age: Int
enum CodingKeys: String, CodingKey {
case name, age
}
enum NameCodingKeys: String, CodingKey {
case firstName, lastName
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
age = try container.decode(Int.self, forKey: .age)
let name = try container.nestedContainer(keyedBy: NameCodingKeys.self, forKey: .name)
firstName = try name.decode(String.self, forKey: .firstName)
lastName = try name.decode(String.self, forKey: .lastName)
}
}
let data = json.data(using: .utf8)
let decoder = JSONDecoder()
let user = try decoder.decode([User].self, from: data!)
print(user)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment