[iOS] Codable

JSON是目前受到廣泛應用的資料形式, 但在Swift 4以前, 解析JSON到對象裡面並不是一件容易的事情, 有些人會特別寫framework或使用第3方framework來專門處理JSON資料的轉換. Swift 4之後, Codable的出現讓大家可以更輕鬆的處理JSON資料了.

這邊直接用code說明:

class ViewController: UIViewController {
    
    //定義json資料
    let jsonString = """   
    {
        "name": "Frank",
        "age":  "1",
        "adress2": null
    }
    """.data(using: .utf8)!
    
    //對應的struct
    struct Student: Codable { 
        let name: String
        let age: Int?  //注意這邊型態為Int, 
        let adress: String? //若參數可能為null或空值, 需設為optional, 否則轉換會失敗
        
        //自定義struct的properity與json的Key值相對應, 可省略
        enum CodingKeys: String, CodingKey {  
            case name
            case age
            case adress = "adress2"
        }
        
        //自己處理每個properity的轉換, 可省略. 
        //這邊是因為age的形態為Int, 但json對應到的值為String的"1", 無法直接轉換
        init(from decoder: Decoder) throws {
            let container = try decoder.container(keyedBy: CodingKeys.self)
            let name = try? container.decode(String.self, forKey: .name)
            let age = try? container.decode(String.self, forKey: .age) 
            let ageInt = (age != nil) ? Int(age!) : 0  //轉換String to Int
            let adress = try? container.decode(String.self, forKey: .adress)

            self.init(name: name, age: ageInt, adress: adress)
        }
        
        init(name: String?, age: Int?, adress:String?) {
            self.name = name ?? ""
            self.age = age
            self.adress = adress ?? ""
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        guard let student = try? JSONDecoder().decode(Student.self, from: self.jsonString) else {
            print("Error: Couldn't decode data into Student")
            return
        }
        
        print(student)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

Last updated