Created
October 8, 2018 17:57
-
-
Save Ceri-anne/7ad252a7f3933ac39a2441818b4f71cd 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 | |
struct User: Decodable { | |
var firstName: String | |
var lastName: String | |
var pets: [Pet] | |
struct Pet: Decodable { | |
var species: String | |
var breed: String | |
var name: String | |
var age: Int | |
} | |
enum CodingKeys: String, CodingKey { | |
case firstName, lastName, pets | |
} | |
public init(from decoder: Decoder) throws { | |
let container = try decoder.container(keyedBy: CodingKeys.self) | |
firstName = try container.decode(String.self, forKey: .firstName) | |
lastName = try container.decode(String.self, forKey: .lastName) | |
pets = try container.decode([Pet].self, forKey: .pets) | |
} | |
} | |
let data = """ | |
{ | |
"firstName": "Beryl", | |
"lastName": "Test", | |
"pets": [ | |
{ | |
"species": "cat", | |
"breed": "Persian", | |
"name": "Sirius", | |
"age": 2 | |
}, | |
{ | |
"species": "dog", | |
"breed": "spaniel", | |
"name": "Minerva", | |
"age": 5 | |
}, | |
] | |
} | |
""".data(using: .utf8)! | |
let user = try? JSONDecoder().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