Swift 的 JSON 解析一直是一件很麻煩的事, 在 Swift3 中請求一個數(shù)據(jù)后可能要進行如下操作(比如服務(wù)器返回一個數(shù)組):
if let jsonObject = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) {
if let objectList = jsonObject as? [Any] {
for object in objectList {
if let object = object as? [String: Any] {
// use object
}
}
}
}
經(jīng)過千辛萬苦終于拿到了這個 object , 然而噩夢才剛剛開始
轉(zhuǎn)成 [String: Any]
的 object 基本上沒法用, 很多時候我們還需要去拿每個 key 和 value 再賦給我們自己定義好的 struct / class (又是一長串的 if let as
)
當然, 目前解決這個問題還是有一些辦法的, 比如可以去嘗試使用 SwiftyJSON 直接當原生的 Array / Dictionary 用, 或者更高級的 Argo, 直接將 JSON data 映射到自己定義的 struct
在 Swift4 中, Swift Standard Library 帶來的新的類和協(xié)議支持原生的 JSON 解析. 甚至不只是 JSON, 只要是 encoding / decoding 的轉(zhuǎn)化都可以支持(比如 plist)
關(guān)于 Swift4 Codable
在 Swfit4 中新添加了一個復(fù)合協(xié)議 typealias Codable = Decodable & Encodable
, 想進行 encoding / decoding 只要實現(xiàn)這個協(xié)議即可. 而且根據(jù)需要, 如果只是從服務(wù)器取數(shù)據(jù)或只是向服務(wù)器發(fā)數(shù)據(jù)完全可以只實現(xiàn)其中一個, 接下來先來試驗下 Decodable 協(xié)議. 先找一個 API, 就隨便找了一個項目直接用 github 的 API https://api.github.com/repos/bewils/IWantTheGreenOne. 首先可以看看返回的數(shù)據(jù)結(jié)構(gòu): 因為只取了一個 repository 所以可以看到返回的結(jié)構(gòu)也很簡單, 按照這個結(jié)構(gòu)寫出如下 struct
struct Repo: Decodable {
var `private`: Bool
var html_url: String
var description: String?
}
這里只取了其中的三個屬性, 即只解析返回的 data 的這三個字段, 然后嘗試發(fā)送請求并解析返回的數(shù)據(jù)
if let url = URL(string: "https://api.github.com/repos/bewils/IWantTheGreenOne") {
let session = URLSession(configuration: .default)
session.dataTask(with: url) { (data, _, err) in
guard err == nil else { return }
guard let data = data else { return }
if let repo = try? JSONDecoder().decode(Repo.self, from: data) {
print(repo)
} else {
print("JSON parse failed")
}
}.resume()
}
奇跡出現(xiàn)了, 很快控制臺里就輸出了 Repo(private: false, html_url: "https://github.com/bewils/IWantTheGreenOne", description: Optional("SpriteKit Game"))
這樣的文字. 我們幾乎沒做什么事, 一如既往的網(wǎng)絡(luò)請求, 在回調(diào)函數(shù)中利用同樣是 Swift4 中新加入的 JSONDecoder 類來按照 Repo 的模型解析 data, 然后就成功的輸出了解析結(jié)果
Codable 便利的一點還在于 Swift 中給出了這個協(xié)議的默認實現(xiàn), 就像 Repo 直接遵從 Decodable 沒有寫解析的任何方法就能通過 JSONDecoder 解析出來
同時在聲明 Repo 時我們將 description 聲明成了 String? 的類型, 這樣如果返回的數(shù)據(jù)里沒有這個字段只會解析出 nil 而不會報錯
關(guān)于字段名
第一個字段 private
是 Swift 的關(guān)鍵字, 當做變量名的時候只能用 `` 包起來, 那要不換個名字改成 jurisdiction
. 運行, 好的, 報錯: 沒有 jurisdicition 這個字段
這只是一種情況, 還有比如返回的 JSON 的 key 是用 _ 分割的命名, 而 Swift 的代碼風(fēng)格一般是駝峰命名, 這時就會有字段名不對應(yīng)的問題, 為了解決這個問題, 可以在 Repo 的內(nèi)部聲明一個遵從 CodingKey 的叫 CodingKeys 枚舉值
struct Repo: Decodable {
var jurisdiction: Bool
var htmlUrl: String
var description: String?
enum CodingKeys: String, CodingKey {
case jurisdiction = "private"
case htmlUrl = "html_url"
case description
}
}
重新運行, 又一次成功地解析出了 Repo: Repo(jurisdiction: false, htmlUrl: "https://github.com/bewils/IWantTheGreenOne", description: Optional("SpriteKit Game"))
.
通過使用 CodingKey 的方式重新定義 JSON key 和屬性名的對應(yīng)關(guān)系是很好用的, 但這里還有一個小問題, 就是如果使用 CodingKey 就必須吧所有的屬性和 key 都寫進去, 比如 Repo 中雖然 description 不需要轉(zhuǎn)化還是要寫進去, 否則這次會找不到 description 對應(yīng)的 key (如果有 50 個屬性的對象為了一個屬性而使用 CodingKeys 也是很慘的...)
關(guān)于嵌套結(jié)構(gòu)
可以看到從 API 返回的數(shù)據(jù)雖然是基本的 Dictionary 結(jié)構(gòu), 但里面還是有一個 owner
的字段屬于嵌套的結(jié)構(gòu), Swift4 中解析嵌套結(jié)構(gòu)的方法非常簡單: 也直接嵌套一個就可以了
struct Owner: Decodable {
var login: String
var id: Int
var avatar_url: String
}
struct Repo: Decodable {
var jurisdiction: Bool
var htmlUrl: String
var description: String?
var owner: Owner
enum CodingKeys: String, CodingKey {
case jurisdiction = "private"
case htmlUrl = "html_url"
case description
case owner
}
}
新添加了一個 Owner 的 struct, 然后加到 Repo 中并且添加一個 CodingKey
運行, 輸出: Repo(jurisdiction: false, htmlUrl: "https://github.com/bewils/IWantTheGreenOne", description: Optional("SpriteKit Game"), owner: __lldb_expr_36.Owner(login: "bewils", id: 16081099, avatar_url: "https://avatars3.githubusercontent.com/u/16081099?v=4"))
(簡直完美, 此處應(yīng)有掌聲 ???
關(guān)于數(shù)組
通過上面的過程已經(jīng)可以將 Repo 成功解析出來了, 無論多復(fù)雜的 JSON, 只要是 key-value, 無論嵌套多深都是一樣的寫法
然而如果返回的是一個數(shù)組呢? https://api.github.com/users/bewils/repos
關(guān)于數(shù)組的解析將會分為兩部分: 二逼程序員和文藝程序員
二逼程序員
再聲明一個 stuct
struct UserRepos {
var repoList: [Repo]
}
因為返回的是一個數(shù)組, 沒有 key 所以通過默認方法肯定轉(zhuǎn)換不來, 自定義去實現(xiàn) Decodable
extension UserRepos: Decodable {
init(from decoder: Decoder) throws {
repoList = []
var values = try decoder.unkeyedContainer()
while !values.isAtEnd {
let repo = try values.decode(Repo.self)
repoList.append(repo)
}
}
}
自定義實現(xiàn)的過程中首先通過 decoder 取出 unkeyedContainer 即初步解析為數(shù)組型的結(jié)構(gòu), 如果這時輸出的話可以看到 values 就是我們要的數(shù)組, 然后順手開始 for in
, values 的類型是 UnkeyedDecodingContainer
, 但竟然不遵從 Sequence
協(xié)議…沒辦法遍歷這可是個難題, 而且查看 values 的其他屬性 isAtEnd = false, count = 31
也證明了 values 應(yīng)該是可以遍歷的
最后發(fā)現(xiàn) UnkeyedDecodingContainer
的遍歷方法就像一個隊列, 每次調(diào)用 decode 就出一個, 然后通過 isAtEnd
來終止循環(huán)就可以了
if let url = URL(string: "https://api.github.com/users/bewils/repos") {
let session = URLSession(configuration: .default)
session.dataTask(with: url, completionHandler: { (data, _, err) in
guard err == nil else { return }
guard let data = data else { return }
do {
// 二逼程序員解析法
let repos = try JSONDecoder().decode(UserRepos.self, from: data)
print(repos.repoList)
} catch let err {
print(err)
}
}).resume()
}
這樣就通過自定義實現(xiàn) Decodable 成功地解析出了返回的數(shù)組
文藝程序員
文藝程序員的解析方法呢?
let repos = try JSONDecoder().decode([Repo].self, from: data)
最后
Swift4 中提供的 Codable 使得解析 JSON 變的極其方便, 這篇文章中主要討論了 Decodable, 關(guān)于 Encodable 基本上就是 Decodable 的反向操作, 就不在這里討論了
本文的 demo 代碼放在如下地址 SwiftCodable