在iOS App中使用JSONDecoder快速剖析JSON資料

戴谷州Ken Tai

  • 恆逸教育訓練中心-資深講師
  • 技術分類:Mobile行動應用開發

 

 

Swift 4開始提供了JSONDecoder 類別可以快速剖析從 Server 端接收 JSON 格式的資料。而 JSONDecoder.decode 方法所需輸入的參數必須是實作Decodable protocol的 struct 或 class。 要剖析的JSON資料:

    [{
        "id": "1",
        "cate_name": "iPod touch"
    }, {
        "id": "2",
        "cate_name": "iPod nano"
    }, {
        "id": "3",
        "cate_name": "iPod shuffle"
    }, {
        "id": "4",
        "cate_name": "iPhone"
    }, {
        "id": "5",
        "cate_name": "iPad"
    }, {
        "id": "6",
        "cate_name": "Apple原廠配件"
    }]    

首先,先定義資料型別,該型別必須實作Decodable protocol,並建立巢狀列舉型別CodingKeys,用來定義JSON資料的實際Key值。

    struct Prod: Decodable {
        let id: String
        let name: String
    
        enum CodingKeys : String, CodingKey {
            case id
            case name = "cate_name"
        }
    }    

利用URLSession進行網路連線,並使用JSONDecoder().decode()方法將JSON字串直接轉換成先前定義的資料型別物件:

    let url = URL(string:"http://ikenapp.appspot.com/json/getCategory.jsp")
    let session = URLSession.shared
    let task = session.dataTask(with: URLRequest(url: url!)) { (data, res, error) in
        if error != nil{
           print(error!)
           return
        }
        guard let list = try? JSONDecoder().decode([Prod].self, from: data!) else {
           print("Error: Couldn't decode data into Products")
           return
        }
        for obj in list{
           print("[\(obj.id)] : \(obj.name)")
        }
    }
    task.resume()    

輸出結果:

    [1] : iPod touch
    [2] : iPod nano
    [3] : iPod shuffle
    [4] : iPhone
    [5] : iPad
    [6] : Apple原廠配件    

是不是很簡單!