Skip to content

Instantly share code, notes, and snippets.

@slimlime
Forked from magicien/Swift4_JSON_03.swift
Created December 17, 2018 05:58
Show Gist options
  • Save slimlime/4412525694d9c9b640d4d44b9d47e96a to your computer and use it in GitHub Desktop.
Save slimlime/4412525694d9c9b640d4d44b9d47e96a 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 uid: Int
let userName: String
let url: URL?
var counter: Int = 0
enum CodingKeys: String, CodingKey {
case uid = "user_id"
case userName = "user_name"
case url
}
}
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