SwiftyJSON
SwiftyJSON是一個開源的庫,能夠幫助開發(fā)者在Swift中更輕松地使用JSON。愛掏網(wǎng) - it200.comSwift對類型非常嚴格,所以在Swift中處理JSON非常困難。愛掏網(wǎng) - it200.comSwiftyJSON提供了一種更好的處理JSON數(shù)據(jù)的方法。愛掏網(wǎng) - it200.com
SwiftyJSON是一個Swift框架,旨在解決常規(guī)JSON序列化中不需要使用可選鏈的問題。愛掏網(wǎng) - it200.com
在使用SwiftyJSON之前,讓我們看看開發(fā)者在Swift中處理JSON時可能遇到的煩惱。愛掏網(wǎng) - it200.com例如,如果你要在一個JSON對象中找到第一本書的名稱,你的代碼可能會像下面這樣:
if let jsonObject = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments) as? [[String: AnyObject]],
let bookName = (jsonObject[0]["book"] as? [String: AnyObject])?["name"] as? String {
//Now, you can use the book name
}
你可以看到上面的代碼非常復雜且不易閱讀。愛掏網(wǎng) - it200.com
通過使用SwiftyJSON,代碼將被大大簡化,如下所示:
let json = JSON(data: data)
if let bookName = json[0]["book"]["name"].string {
//Now, you can use the book name
}
SwiftyJSON消除了檢查每個字段的要求,如果它們中的任何一個無效,則返回nil。愛掏網(wǎng) - it200.com
下載SwiftJSON
您可以直接從GitHub下載或克隆SwityJSON:
https://github.com/SwiftyJSON/SwiftyJSON
如何使用SwiftyJSON
要使用SwiftyJSON,您需要從Git存儲庫中下載正確的版本。愛掏網(wǎng) - it200.com只需將”SwiftyJSON.swift”拖到您的項目中并導入到您的類中即可:
import SwiftyJSON
您可以通過使用初始化函數(shù)來創(chuàng)建自己的JSON對象。愛掏網(wǎng) - it200.com有兩種方法可以創(chuàng)建自己的JSON對象:
let jsonObject = JSON(data: dataObject)
或者
let jsonObject = JSON(jsonObject) //This could be a string in a JSON format for example
你可以使用下標來訪問你的數(shù)據(jù)。愛掏網(wǎng) - it200.com
let firstObjectInAnArray = jsonObject[0]
let nameOfFirstObject = jsonObject[0]["name"]
您可以將您的值解析為特定的數(shù)據(jù)類型,它將返回一個可選值:
let nameOfFirstObject = jsonObject[0]["name"].string //This will return the name as a string
let nameOfFirstObject = jsonObject[0]["name"].double //This will return null
您也可以將您的路徑編譯成一個swift數(shù)組:
let convolutedPath = jsonObject[0]["name"][2]["lastName"]["firstLetter"].string
與下面的相同:
let convolutedPath = jsonObject[0, "name", 2, "lastName", "firstLetter"].string
SwiftyJSON有打印自己錯誤的功能:
if let name = json[1337].string {
//You can use the value - it is valid
} else {
print(json[1337].error) // "Array[1337] is out of bounds" - You cant use the value
}
如果您需要向您的JSON對象寫入內(nèi)容,您可以再次使用下標:
var originalJSON:JSON = ["name": "Jack", "age": 18]
originalJSON["age"] = 25 //This changes the age to 25
originalJSON["surname"] = "Smith" //This creates a new field called "surname" and adds the value to it.
如果您需要JSON的原始字符串,例如如果您需要將其寫入文件,您可以使用原始值獲取它。愛掏網(wǎng) - it200.com
if let string = json.rawString() { //This is a String object
//Write the string to a file if you like
}
if let data = json.rawData() { //This is an NSData object
//Send the data to your server if you like
}