SwiftyJsonが便利だけど、Swift表標準機能であるCodableもそこそこ使いやすかったのでメモ
実践的ではないけど一番シンプルなCodableでjsonをinstanceに変換する例
structにCodableを継承させて、jsonをデータ変変換した後、JSONDecoder.decodeを使うだけ。
ただ、Codableで定義した型情報と、jsonの形が厳密に同じである必要がある。そのため、jsonのキーが一つでも欠けているとエラーになる。
var data = """
{
"name": "Bob",
"age": 20,
"sex": "male",
}
""".data(using: .utf8)!
struct User: Codable {
let name: String
let age: Int
}
let users: User = try JSONDecoder().decode(User.self, from: data)
users // User(name: 1, age: 20)
実践的なCodableの使い方(jsonのキーが欠ける場合)
structを以下のようにclass変変更し、init関数内で初期化を行う。
純粋なswiftで書かれているので、分かりやすい。
var data = """
{
"name": "Bob",
"age": 20,
}
""".data(using: .utf8)!
class User: Codable {
var name: String
var age: Int
var sex: String? // sexがjsonにない!
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.name = try container.decodeIfPresent(String.self, forKey: .name) ?? nil
self.age = try container.decodeIfPresent(Int.self, forKey: .age) ?? nil
self.sex = try container.decodeIfPresent(String.self, forKey: .sex) ?? nil
}
}
let users: User = try JSONDecoder().decode(User.self, from: data)
users // User(name: "Bob", age: 20, sex: nil)
まとめ
SwiftyJsonと比べCodableもそんなに悪くない。