JSON(JavaScript Object Notation)是一種輕量級的數(shù)據(jù)交換格式,常用于前后端數(shù)據(jù)傳輸。
官方文檔:Using JSON with Custom Types
JSON 介紹:JavaScript Object Notation
SwiftyJSON是一個用于解析JSON數(shù)據(jù)的Swift庫。它提供了簡單易用的API,使得解析JSON數(shù)據(jù)變得更加方便快捷。優(yōu)點是耦合性低,靈活性高,易用性強。我們可以快速上手使用。缺點是不像Codable或者Mapper那樣有明顯的映射關(guān)系。
基本使用
本文中的JSON數(shù)據(jù)格式
本地文件名:BookList.json
{
"list": [
{
"desc": "資布給回管并轉(zhuǎn)例快真應(yīng)社斗。需計分很稱軍次再派非示開。任狀般目程公節(jié)石達(dá)油第易色常表報來。義造手群特做種響必總算政更。能段委百千工則達(dá)教圖戰(zhàn)越。他議她級對和報門各路子至設(shè)去見。",
"name": "蔡平",
"num": 25
},
{
"desc": "火型己江約統(tǒng)門山強前領(lǐng)周支團京多支。年會選品科還放們約石通次知酸育。團今年縣受產(chǎn)共四金識次去號經(jīng)音統(tǒng)學(xué)。當(dāng)斯幾精道口米由究即報熱向?qū)]^你熱。",
"name": "吳霞",
"num": 28
},
}
我們可以通過本地讀取文件獲取JSON對象,也可以網(wǎng)絡(luò)獲取
本地獲取
func readLocalJSON() {
let json = EasyTestModel.getLocalJSON("BookList", "json")
updateModel(json)
}
/// 本地獲取JSON
static func getLocalJSON(_ forResourceName: String, _ type: String) -> JSON {
let path = Bundle.main.path(forResource: forResourceName, ofType: type) ?? ""
var json = JSON()
do {
let data: Data = try Data(contentsOf: URL(fileURLWithPath: path))
json = try JSON(data: data)
return json
} catch {
print("讀取本地文件失敗:\(error.localizedDescription)")
}
return json
}
網(wǎng)絡(luò)獲取
func getNetModel() {
let url = GlobalConfig.BOOKLIST_URL
let parameters = ["key": "value"]
DispatchQueue.global().async {
Alamofire.request(url, method: .get, parameters: parameters, encoding: URLEncoding.default, headers: nil).responseJSON(completionHandler: { response in
// 處理響應(yīng)結(jié)果
if let value = response.result.value {
let json = JSON(value)
self.updateModel(json)
}
if let error = response.result.error {
print("Response error: \(error)")
}
})
}
}
獲取了JSON對象后我們可以靈活的操作,可以使用點語法或下標(biāo)訪問JSON數(shù)據(jù)
let num = element["num"].intValue // 獲取名為"num"的整數(shù)值
let name = element["name"].stringValue // 獲取名為"name"的字符串值
let height = element["height"].doubleValue // 獲取名為"height"的浮點數(shù)值
let isBook = element["isBook"].boolValue // 獲取名為"isBook"的布爾值
也可以封裝成對象
struct Book {
var authorNumber: Int
var authorName: String
var desc: String
}
func updateModel(_ json: JSON) {
let bookArr = json["list"].arrayValue
for element in bookArr {
let num = element["num"].intValue
let name = element["name"].stringValue
let desc = element["desc"].stringValue
let book = Book(authorNumber: num, authorName: name, desc: desc)
bookArray.append(book)
}
mTableView.reloadData()
}