Skip to content

Instantly share code, notes, and snippets.

@magicien
Created August 22, 2017 09:48
Show Gist options
  • Save magicien/83fabcaca7f9f39182875bc60bbd2aab to your computer and use it in GitHub Desktop.
Save magicien/83fabcaca7f9f39182875bc60bbd2aab to your computer and use it in GitHub Desktop.
import Foundation
let json = """
{
"user_id": 1,
"user_name": "magicien",
"friends": [
{
"user_id": 2,
"is_best_friend": true
}
]
}
""".data(using: .utf8)!
struct UserInfo: Codable {
let user_id: Int
let user_name: String
let url: URL?
struct Friend: Codable {
let user_id: Int
let is_best_friend: Bool
}
let friends: [Friend]
}
let decoder = JSONDecoder()
do {
let userInfo = try decoder.decode(UserInfo.self, from: json)
print(userInfo)
} catch DecodingError.keyNotFound(let key, let context) {
print("keyNotFound: \(key): \(context)")
} catch {
print("\(error.localizedDescription)")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment