SwiftyJSON

SwiftyJSON 是一個 Swift 框架,用於消除普通 JSON 序列化中可選連結的需要。

你可以在此處下載: https//github.com/SwiftyJSON/SwiftyJSON

如果沒有 SwiftyJSON,你的程式碼將如下所示,以查詢 JSON 物件中第一本書的名稱:

if let jsonObject = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments) as? [[String: AnyObject]],
let bookName = (jsonObject[0]["book"] as? [String: AnyObject])?["name"] as? String {
    //We can now use the book name
}

在 SwiftyJSON 中,這非常簡單:

let json = JSON(data: data)
if let bookName = json[0]["book"]["name"].string {
    //We can now use the book name
}

它不需要檢查每個欄位,因為如果它們中的任何一個無效,它將返回 nil。

要使用 SwiftyJSON,請從 Git 儲存庫下載正確的版本 - Swift 3 有一個分支。只需將“SwiftyJSON.swift”拖到專案中並匯入到你的類中:

import SwiftyJSON

你可以使用以下兩個初始值設定項建立 JSON 物件:

let jsonObject = JSON(data: dataObject)

要麼

let jsonObject = JSON(jsonObject) //This could be a string in a JSON format for example

要訪問你的資料,請使用下標:

let firstObjectInAnArray = jsonObject[0]
let nameOfFirstObject = jsonObject[0]["name"]

然後,你可以將值解析為某種資料型別,這將返回一個可選值:

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 陣列:

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 物件,可以再次使用下標:

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 的原始字串,例如,如果你需要將其寫入檔案,則可以獲取原始值:

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
}