Skip to content

Instantly share code, notes, and snippets.

@Ceri-anne
Created October 8, 2018 17:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Ceri-anne/7ad252a7f3933ac39a2441818b4f71cd to your computer and use it in GitHub Desktop.
Save Ceri-anne/7ad252a7f3933ac39a2441818b4f71cd to your computer and use it in GitHub Desktop.
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