Created
April 19, 2019 08:46
-
-
Save JarvisTheAvenger/b5a47a8d8b88a8f45e861d6064bdadb8 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
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