在Swift中要如何解析json資料?透過Codable輕鬆辦到!

【 Swift 】

在iOS的開發中時常需要透過JSON檔案做資料交換,這個時候可以使用Codable做到這一點。Codable可以解析JSON檔案也可以快速的將文字包裝成JSON檔。

Codable is a type alias for the Encodable and Decodable protocols. When you use Codable as a type or a generic constraint, it matches any type that conforms to both protocols.

技術相關 :Swift JSON Codable CodingKeys

使用之前我們需要先建構我們要的JSON內容, CodingKey的部分可以將原本的變數轉換成我們想要用的變數,例如當userName回來後,我希望可以用"name"來表示比較簡潔,這部分看個人需求,非必要。


struct openData: Codable {
     var userName :String
     var userID :String
     var phoneNumber :String
    
    enum CodingKeys: String, CodingKey {
        case userName = "name"
        case userID =  "id"
        case phoneNumber = "number"
      }
}

JSON的格式建好後就可以透過以下方式解析


func fetchJsonData()
    {
        let session = URLSession.shared.dataTask(with: url) { (data, response, error) in
            if let error = error { assertionFailure(error.localizedDescription) }
            guard let data = data else { return }
            do{
                let decodableData = try JSONDecoder().decode(openData.self, from: data)
                let name = decodableData.name
                let id = decodableData.id
                let phoneN = decodableData.number
                print(name,id,phoneN)//Do something.... 
            }catch{
                assertionFailure("parsing fail")
            }
        }
        session.resume()
    }

以上需要注意到,解析後的JSON是透過CodinKeys裡面新的名字取得資料,而不是透過原本的變數,若沒有CodinKeys需求就直接使用原本命名的變數即可,例如decodableData.userName。